@creativeorange/azure-text-to-speech 1.0.1 → 1.1.0

Sign up to get free protection for your applications and to get access to all the features.
@@ -5855,38 +5855,18 @@ class TextToSpeech {
5855
5855
  __publicField(this, "player");
5856
5856
  __publicField(this, "synthesizer");
5857
5857
  __publicField(this, "previousWordBoundary");
5858
+ __publicField(this, "interval");
5859
+ __publicField(this, "wordEncounters", []);
5860
+ __publicField(this, "originalHighlightDivInnerHTML", "");
5861
+ __publicField(this, "currentWord", "");
5862
+ __publicField(this, "currentOffset", 0);
5858
5863
  this.key = key;
5859
5864
  this.region = region;
5860
5865
  this.voice = voice;
5861
5866
  }
5862
5867
  async start() {
5863
- setInterval(() => {
5864
- var _a;
5865
- if (this.player !== void 0 && this.highlightDiv) {
5866
- const currentTime = this.player.currentTime;
5867
- let wordBoundary;
5868
- for (const e of this.wordBoundryList) {
5869
- if (currentTime * 1e3 > e.audioOffset / 1e4) {
5870
- wordBoundary = e;
5871
- } else {
5872
- break;
5873
- }
5874
- }
5875
- if (wordBoundary !== void 0) {
5876
- if (~[".", ",", "!", "?"].indexOf(wordBoundary.text)) {
5877
- wordBoundary = (_a = this.previousWordBoundary) != null ? _a : void 0;
5878
- }
5879
- this.previousWordBoundary = wordBoundary;
5880
- this.highlightDiv.innerHTML = this.textToRead.substring(0, wordBoundary.textOffset) + "<span class='co-tts-highlight'>" + wordBoundary.text + "</span>" + this.textToRead.substring(wordBoundary.textOffset + wordBoundary.wordLength);
5881
- } else {
5882
- this.highlightDiv.innerHTML = this.textToRead;
5883
- }
5884
- }
5885
- }, 50);
5886
5868
  await this.registerBindings(document);
5887
5869
  }
5888
- async synthesis() {
5889
- }
5890
5870
  async registerBindings(node) {
5891
5871
  const nodes = node.childNodes;
5892
5872
  for (let i = 0; i < nodes.length; i++) {
@@ -5918,6 +5898,7 @@ class TextToSpeech {
5918
5898
  node.addEventListener("click", async (_) => {
5919
5899
  var _a;
5920
5900
  this.stopPlayer();
5901
+ await this.createInterval();
5921
5902
  this.clickedNode = node;
5922
5903
  const referenceDiv = document.getElementById(attr.value);
5923
5904
  if (!referenceDiv) {
@@ -5930,6 +5911,7 @@ class TextToSpeech {
5930
5911
  }
5931
5912
  if (referenceDiv.hasAttribute("co-tts.highlight")) {
5932
5913
  this.highlightDiv = referenceDiv;
5914
+ this.originalHighlightDivInnerHTML = referenceDiv.innerHTML;
5933
5915
  }
5934
5916
  this.startSynthesizer(node, attr);
5935
5917
  });
@@ -5937,6 +5919,7 @@ class TextToSpeech {
5937
5919
  async handleAjaxModifier(node, attr) {
5938
5920
  node.addEventListener("click", async (_) => {
5939
5921
  this.stopPlayer();
5922
+ await this.createInterval();
5940
5923
  this.clickedNode = node;
5941
5924
  const response = await fetch(attr.value, {
5942
5925
  method: `GET`
@@ -5948,9 +5931,11 @@ class TextToSpeech {
5948
5931
  async handleDefault(node, attr) {
5949
5932
  node.addEventListener("click", async (_) => {
5950
5933
  this.stopPlayer();
5934
+ await this.createInterval();
5951
5935
  this.clickedNode = node;
5952
5936
  if (node.hasAttribute("co-tts.highlight")) {
5953
5937
  this.highlightDiv = node;
5938
+ this.originalHighlightDivInnerHTML = node.innerHTML;
5954
5939
  }
5955
5940
  if (attr.value === "") {
5956
5941
  this.textToRead = node.innerHTML;
@@ -5960,27 +5945,51 @@ class TextToSpeech {
5960
5945
  this.startSynthesizer(node, attr);
5961
5946
  });
5962
5947
  }
5948
+ async handleWithoutClick(node, attr) {
5949
+ this.stopPlayer();
5950
+ await this.createInterval();
5951
+ this.clickedNode = node;
5952
+ if (node.hasAttribute("co-tts.highlight")) {
5953
+ this.highlightDiv = node;
5954
+ this.originalHighlightDivInnerHTML = node.innerHTML;
5955
+ }
5956
+ if (attr.value === "") {
5957
+ this.textToRead = node.innerHTML;
5958
+ } else {
5959
+ this.textToRead = attr.value;
5960
+ }
5961
+ this.startSynthesizer(node, attr);
5962
+ }
5963
5963
  async handleStopModifier(node, attr) {
5964
5964
  node.addEventListener("click", async (_) => {
5965
5965
  await this.stopPlayer();
5966
+ document.dispatchEvent(new CustomEvent("COAzureTTSStoppedPlaying", {}));
5966
5967
  });
5967
5968
  }
5968
5969
  async handlePauseModifier(node, attr) {
5969
5970
  node.addEventListener("click", async (_) => {
5971
+ await this.clearInterval();
5970
5972
  await this.player.pause();
5973
+ document.dispatchEvent(new CustomEvent("COAzureTTSPausedPlaying", {}));
5971
5974
  });
5972
5975
  }
5973
5976
  async handleResumeModifier(node, attr) {
5974
5977
  node.addEventListener("click", async (_) => {
5978
+ await this.createInterval();
5975
5979
  await this.player.resume();
5980
+ document.dispatchEvent(new CustomEvent("COAzureTTSResumedPlaying", {}));
5976
5981
  });
5977
5982
  }
5978
5983
  async stopPlayer() {
5984
+ await this.clearInterval();
5979
5985
  if (this.highlightDiv !== void 0) {
5980
- this.highlightDiv.innerHTML = this.textToRead;
5986
+ this.highlightDiv.innerHTML = this.originalHighlightDivInnerHTML;
5981
5987
  }
5982
5988
  this.textToRead = "";
5989
+ this.currentWord = "";
5990
+ this.originalHighlightDivInnerHTML = "";
5983
5991
  this.wordBoundryList = [];
5992
+ this.wordEncounters = [];
5984
5993
  if (this.player !== void 0) {
5985
5994
  this.player.pause();
5986
5995
  }
@@ -5990,22 +5999,29 @@ class TextToSpeech {
5990
5999
  async startSynthesizer(node, attr) {
5991
6000
  this.speechConfig = SpeechConfig.fromSubscription(this.key, this.region);
5992
6001
  this.speechConfig.speechSynthesisVoiceName = `Microsoft Server Speech Text to Speech Voice (${this.voice})`;
5993
- this.speechConfig.speechSynthesisOutputFormat = 8;
6002
+ this.speechConfig.speechSynthesisOutputFormat = SpeechSynthesisOutputFormat.Audio24Khz160KBitRateMonoMp3;
5994
6003
  this.player = new SpeakerAudioDestination();
5995
6004
  this.audioConfig = AudioConfig.fromSpeakerOutput(this.player);
5996
6005
  this.synthesizer = new SpeechSynthesizer(this.speechConfig, this.audioConfig);
5997
6006
  this.synthesizer.wordBoundary = (s, e) => {
5998
6007
  this.wordBoundryList.push(e);
5999
6008
  };
6000
- this.player.onAudioEnd = () => {
6009
+ this.player.onAudioEnd = async () => {
6001
6010
  this.stopPlayer();
6002
6011
  if (this.clickedNode.hasAttribute("co-tts.next")) {
6003
6012
  const nextNode = document.getElementById(this.clickedNode.getAttribute("co-tts.next"));
6004
- if (nextNode) {
6013
+ if (nextNode && nextNode.attributes.getNamedItem("co-tts.text")) {
6014
+ this.handleWithoutClick(nextNode, nextNode.attributes.getNamedItem("co-tts.text"));
6015
+ } else if (nextNode) {
6005
6016
  nextNode.dispatchEvent(new Event("click"));
6006
6017
  }
6018
+ } else {
6019
+ document.dispatchEvent(new CustomEvent("COAzureTTSFinishedPlaying", {}));
6007
6020
  }
6008
6021
  };
6022
+ this.player.onAudioStart = async () => {
6023
+ document.dispatchEvent(new CustomEvent("COAzureTTSStartedPlaying", {}));
6024
+ };
6009
6025
  this.synthesizer.speakTextAsync(
6010
6026
  this.textToRead,
6011
6027
  () => {
@@ -6018,5 +6034,55 @@ class TextToSpeech {
6018
6034
  }
6019
6035
  );
6020
6036
  }
6037
+ async clearInterval() {
6038
+ clearInterval(this.interval);
6039
+ }
6040
+ async createInterval() {
6041
+ this.interval = setInterval(() => {
6042
+ var _a;
6043
+ if (this.player !== void 0 && this.highlightDiv) {
6044
+ const currentTime = this.player.currentTime;
6045
+ let wordBoundary;
6046
+ for (const e of this.wordBoundryList) {
6047
+ if (currentTime * 1e3 > e.audioOffset / 1e4) {
6048
+ wordBoundary = e;
6049
+ } else {
6050
+ break;
6051
+ }
6052
+ }
6053
+ if (wordBoundary !== void 0) {
6054
+ if (~[".", ",", "!", "?"].indexOf(wordBoundary.text)) {
6055
+ wordBoundary = (_a = this.previousWordBoundary) != null ? _a : void 0;
6056
+ }
6057
+ if (wordBoundary === void 0) {
6058
+ this.highlightDiv.innerHTML = this.originalHighlightDivInnerHTML;
6059
+ } else {
6060
+ if (!this.wordEncounters[wordBoundary.text]) {
6061
+ this.wordEncounters[wordBoundary.text] = 0;
6062
+ }
6063
+ if (this.currentWord !== wordBoundary.text) {
6064
+ this.wordEncounters[wordBoundary.text]++;
6065
+ console.log(this.wordEncounters);
6066
+ this.currentOffset = this.getPosition(
6067
+ this.originalHighlightDivInnerHTML,
6068
+ wordBoundary.text,
6069
+ this.wordEncounters[wordBoundary.text]
6070
+ );
6071
+ this.currentWord = wordBoundary.text;
6072
+ }
6073
+ this.previousWordBoundary = wordBoundary;
6074
+ this.highlightDiv.innerHTML = this.originalHighlightDivInnerHTML.substring(0, this.currentOffset) + "<mark class='co-tts-highlight'>" + wordBoundary.text + "</mark>" + this.originalHighlightDivInnerHTML.substring(this.currentOffset + wordBoundary.wordLength);
6075
+ }
6076
+ } else {
6077
+ this.highlightDiv.innerHTML = this.originalHighlightDivInnerHTML;
6078
+ }
6079
+ }
6080
+ }, 50);
6081
+ }
6082
+ getPosition(string, subString, index) {
6083
+ const regex = new RegExp(`\\b${subString}\\b`, "g");
6084
+ console.log(string.split(regex, index).join(subString), regex, index);
6085
+ return string.split(regex, index).join(subString).length;
6086
+ }
6021
6087
  }
6022
6088
  export { TextToSpeech as default };
@@ -1,8 +1,8 @@
1
- (function(I,R){typeof exports=="object"&&typeof module!="undefined"?module.exports=R():typeof define=="function"&&define.amd?define(R):(I=typeof globalThis!="undefined"?globalThis:I||self,I.CreativeOrangeAzureTextToSpeech=R())})(this,function(){"use strict";var Oi=Object.defineProperty;var _i=(I,R,q)=>R in I?Oi(I,R,{enumerable:!0,configurable:!0,writable:!0,value:q}):I[R]=q;var B=(I,R,q)=>(_i(I,typeof R!="symbol"?R+"":R,q),q);var I={},R,q=new Uint8Array(16);function Mt(){if(!R&&(R=typeof crypto!="undefined"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto!="undefined"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto),!R))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return R(q)}var Tt=/^(?:[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 kt(i){return typeof i=="string"&&Tt.test(i)}for(var A=[],De=0;De<256;++De)A.push((De+256).toString(16).substr(1));function Dt(i){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,t=(A[i[e+0]]+A[i[e+1]]+A[i[e+2]]+A[i[e+3]]+"-"+A[i[e+4]]+A[i[e+5]]+"-"+A[i[e+6]]+A[i[e+7]]+"-"+A[i[e+8]]+A[i[e+9]]+"-"+A[i[e+10]]+A[i[e+11]]+A[i[e+12]]+A[i[e+13]]+A[i[e+14]]+A[i[e+15]]).toLowerCase();if(!kt(t))throw TypeError("Stringified UUID is invalid");return t}function It(i,e,t){i=i||{};var r=i.random||(i.rng||Mt)();if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,e){t=t||0;for(var n=0;n<16;++n)e[t+n]=r[n];return e}return Dt(r)}const zt=()=>It(),E=()=>zt().replace(new RegExp("-","g"),"").toUpperCase();var S;(function(i){i[i.Debug=0]="Debug",i[i.Info=1]="Info",i[i.Warning=2]="Warning",i[i.Error=3]="Error",i[i.None=4]="None"})(S||(S={}));class F{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 F{constructor(e,t,r=S.Info){super(e,r),this.privAudioSourceId=t}get audioSourceId(){return this.privAudioSourceId}}class le extends se{constructor(e){super("AudioSourceInitializingEvent",e)}}class oe extends se{constructor(e){super("AudioSourceReadyEvent",e)}}class Ye extends se{constructor(e){super("AudioSourceOffEvent",e)}}class Ie extends se{constructor(e,t){super("AudioSourceErrorEvent",e,S.Error),this.privError=t}get error(){return this.privError}}class fe extends se{constructor(e,t,r){super(e,t),this.privAudioNodeId=r}get audioNodeId(){return this.privAudioNodeId}}class me extends fe{constructor(e,t){super("AudioStreamNodeAttachingEvent",e,t)}}class Se extends fe{constructor(e,t){super("AudioStreamNodeAttachedEvent",e,t)}}class K extends fe{constructor(e,t){super("AudioStreamNodeDetachedEvent",e,t)}}class et extends fe{constructor(e,t,r){super("AudioStreamNodeErrorEvent",e,t),this.privError=r}get error(){return this.privError}}class Bt extends F{constructor(e,t,r=S.Info){super(e,r),this.privJsonResult=t}get jsonString(){return this.privJsonResult}}class J extends F{constructor(e,t,r=S.Info){super(e,r),this.privConnectionId=t}get connectionId(){return this.privConnectionId}}class xt extends J{constructor(e,t,r){super("ConnectionStartEvent",e),this.privUri=t,this.privHeaders=r}get uri(){return this.privUri}get headers(){return this.privHeaders}}class Nt extends J{constructor(e){super("ConnectionEstablishedEvent",e)}}class Lt extends J{constructor(e,t,r){super("ConnectionClosedEvent",e,S.Debug),this.privReason=r,this.privStatusCode=t}get reason(){return this.privReason}get statusCode(){return this.privStatusCode}}class Ot extends J{constructor(e,t,r){super("ConnectionErrorEvent",e,S.Debug),this.privMessage=t,this.privType=r}get message(){return this.privMessage}get type(){return this.privType}}class tt extends J{constructor(e,t,r){super("ConnectionMessageReceivedEvent",e),this.privNetworkReceivedTime=t,this.privMessage=r}get networkReceivedTime(){return this.privNetworkReceivedTime}get message(){return this.privMessage}}class _t extends J{constructor(e,t,r){super("ConnectionMessageSentEvent",e),this.privNetworkSentTime=t,this.privMessage=r}get networkSentTime(){return this.privNetworkSentTime}get message(){return this.privMessage}}class k extends Error{constructor(e){super(e),this.name="ArgumentNull",this.message=e}}class x extends Error{constructor(e){super(e),this.name="InvalidOperation",this.message=e}}class ze extends Error{constructor(e,t){super(t),this.name=e+"ObjectDisposed",this.message=t}}var w;(function(i){i[i.Text=0]="Text",i[i.Binary=1]="Binary"})(w||(w={}));class Be{constructor(e,t,r,n){if(this.privBody=null,e===w.Text&&t&&typeof t!="string")throw new x("Payload must be a string");if(e===w.Binary&&t&&!(t instanceof ArrayBuffer))throw new x("Payload must be ArrayBuffer");switch(this.privMessageType=e,this.privBody=t,this.privHeaders=r||{},this.privId=n||E(),this.messageType){case w.Binary:this.privSize=this.binaryBody!==null?this.binaryBody.byteLength:0;break;case w.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===w.Binary)throw new x("Not supported for binary message");return this.privBody}get binaryBody(){if(this.privMessageType===w.Text)throw new x("Not supported for text message");return this.privBody}get id(){return this.privId}}class xe{constructor(e,t){this.privStatusCode=e,this.privReason=t}get statusCode(){return this.privStatusCode}get reason(){return this.privReason}}class U{constructor(e){this.privEventListeners={},this.privIsDisposed=!1,this.privConsoleListener=void 0,this.privMetadata=e}onEvent(e){if(this.isDisposed())throw new ze("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 M{static setEventSource(e){if(!e)throw new k("eventSource");M.privInstance=e}static get instance(){return M.privInstance}}M.privInstance=new U;var P;(function(i){i[i.None=0]="None",i[i.Connected=1]="Connected",i[i.Connecting=2]="Connecting",i[i.Disconnected=3]="Disconnected"})(P||(P={}));class L{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 r=this.privList.splice(e,t);return this.triggerSubscriptions(this.privRemoveSubscriptions),r}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 r=0;r<this.privList.length;r++)t.push(e(this.privList[r],r));return new L(t)}where(e){this.throwIfDisposed();const t=new L;for(let r=0;r<this.privList.length;r++)e(this.privList[r],r)&&t.add(this.privList[r]);return t}orderBy(e){this.throwIfDisposed();const r=this.toArray().sort(e);return new L(r)}orderByDesc(e){return this.throwIfDisposed(),this.orderBy((t,r)=>e(r,t))}clone(){return this.throwIfDisposed(),new L(this.toArray())}concat(e){return this.throwIfDisposed(),new L(this.privList.concat(e.toArray()))}concatArray(e){return this.throwIfDisposed(),new L(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 ze("List",this.privDisposeReason)}triggerSubscriptions(e){if(e)for(const t in e)t&&e[t]()}}var it;(function(i){i[i.None=0]="None",i[i.Resolved=1]="Resolved",i[i.Rejected=2]="Rejected"})(it||(it={}));class T{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 Kt(i,e,t){i.then(r=>{try{e&&e(r)}catch(n){if(t)try{if(n instanceof Error){const s=n;t(s.name+": "+s.message)}else t(n)}catch{}}},r=>{if(t)try{if(r instanceof Error){const n=r;t(n.name+": "+n.message)}else t(r)}catch{}})}var rt=globalThis&&globalThis.__awaiter||function(i,e,t,r){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(r.next(c))}catch(p){o(p)}}function u(c){try{h(r.throw(c))}catch(p){o(p)}}function h(c){c.done?s(c.value):n(c.value).then(a,u)}h((r=r.apply(i,e||[])).next())})},ae;(function(i){i[i.Dequeue=0]="Dequeue",i[i.Peek=1]="Peek"})(ae||(ae={}));class ce{constructor(e){this.privPromiseStore=new L,this.privIsDrainInProgress=!1,this.privIsDisposing=!1,this.privDisposeReason=null,this.privList=e||new L,this.privDetachables=[],this.privSubscribers=new L,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 T;return this.privSubscribers&&(this.privSubscribers.add({deferral:e,type:ae.Dequeue}),this.drain()),e.promise}peek(){this.throwIfDispose();const e=new T;return this.privSubscribers&&(this.privSubscribers.add({deferral:e,type:ae.Peek}),this.drain()),e.promise}length(){return this.throwIfDispose(),this.privList.length()}isDisposed(){return this.privSubscribers==null}drainAndDispose(e,t){return rt(this,void 0,void 0,function*(){if(!this.isDisposed()&&!this.privIsDisposing){this.privDisposeReason=t,this.privIsDisposing=!0;const r=this.privSubscribers;if(r){for(;r.length()>0;)r.removeFirst().deferral.resolve(void 0);this.privSubscribers===r&&(this.privSubscribers=r)}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 rt(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 r=e.removeFirst();if(r.type===ae.Peek)r.deferral.resolve(t.first());else{const n=t.removeFirst();r.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 x(this.privDisposeReason):new ze("Queue");if(this.privIsDisposing)throw new x("Queue disposing")}}class we{constructor(e,t,r){if(this.privPayload=null,!t)throw new k("payload");if(e===w.Binary&&t.__proto__.constructor.name!=="ArrayBuffer")throw new x("Payload must be ArrayBuffer");if(e===w.Text&&typeof t!="string")throw new x("Payload must be a string");this.privMessageType=e,this.privPayload=t,this.privId=r||E()}get messageType(){return this.privMessageType}get payload(){return this.privPayload}get textContent(){if(this.privMessageType===w.Binary)throw new x("Not supported for binary message");return this.privPayload}get binaryContent(){if(this.privMessageType===w.Text)throw new x("Not supported for text message");return this.privPayload}get id(){return this.privId}}class Ut{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 r=t.length*2,n=new ArrayBuffer(r),s=new DataView(n);return this.floatTo16BitPCM(s,0,t),n}setString(e,t,r){for(let n=0;n<r.length;n++)e.setUint8(t+n,r.charCodeAt(n))}floatTo16BitPCM(e,t,r){for(let n=0;n<r.length;n++,t+=2){const s=Math.max(-1,Math.min(1,r[n]));e.setInt16(t,s<0?s*32768:s*32767,!0)}}downSampleAudioFrame(e,t,r){if(!e)return null;if(r===t||r>t)return e;const n=t/r,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,p=0;for(;a<h&&a<e.length;)c+=e[a++],p++;o[u++]=c/p}return o}}var Ht=globalThis&&globalThis.__awaiter||function(i,e,t,r){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(r.next(c))}catch(p){o(p)}}function u(c){try{h(r.throw(c))}catch(p){o(p)}}function h(c){c.done?s(c.value):n(c.value).then(a,u)}h((r=r.apply(i,e||[])).next())})};class nt{constructor(e){this.privIsWriteEnded=!1,this.privIsReadEnded=!1,this.privId=e||E(),this.privReaderQueue=new ce}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 x("Stream read has already finished");return this.privReaderQueue.dequeue().then(e=>Ht(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 ce)}throwIfClosed(){if(this.privIsWriteEnded)throw new x("Stream closed")}}class Ne extends nt{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 r=Math.min(e.buffer.byteLength-t,this.privTargetChunkSize-this.privNextBufferReadyBytes),n=new Uint8Array(this.privNextBufferToWrite),s=new Uint8Array(e.buffer.slice(t,r+t));n.set(s,this.privNextBufferReadyBytes),this.privNextBufferReadyBytes+=r,t+=r,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 D extends F{constructor(e,t,r){super(e,t),this.privSignature=r}}class Wt extends D{constructor(e){super("OCSPMemoryCacheHitEvent",S.Debug,e)}}class Vt extends D{constructor(e){super("OCSPCacheMissEvent",S.Debug,e)}}class qt extends D{constructor(e){super("OCSPDiskCacheHitEvent",S.Debug,e)}}class jt extends D{constructor(e){super("OCSPCacheUpdateNeededEvent",S.Debug,e)}}class Gt extends D{constructor(e){super("OCSPMemoryCacheStoreEvent",S.Debug,e)}}class $t extends D{constructor(e){super("OCSPDiskCacheStoreEvent",S.Debug,e)}}class Ft extends D{constructor(e){super("OCSPCacheUpdateCompleteEvent",S.Debug,e)}}class Jt extends D{constructor(){super("OCSPStapleReceivedEvent",S.Debug,"")}}class Qt extends D{constructor(e,t){super("OCSPCacheEntryExpiredEvent",S.Debug,e),this.privExpireTime=t}}class Xt extends D{constructor(e,t,r){super("OCSPCacheEntryNeedsRefreshEvent",S.Debug,e),this.privExpireTime=r,this.privStartTime=t}}class Zt extends D{constructor(e,t,r){super("OCSPCacheHitEvent",S.Debug,e),this.privExpireTime=r,this.privExpireTimeString=new Date(r).toLocaleDateString(),this.privStartTime=t,this.privStartTimeString=new Date(t).toLocaleTimeString()}}class Yt extends D{constructor(e,t){super("OCSPVerificationFailedEvent",S.Debug,e),this.privError=t}}class st extends D{constructor(e,t){super("OCSPCacheFetchErrorEvent",S.Debug,e),this.privError=t}}class ei extends D{constructor(e){super("OCSPResponseRetrievedEvent",S.Debug,e)}}class ti extends D{constructor(e,t){super("OCSPCacheUpdateErrorEvent",S.Debug,e),this.privError=t}}class he extends F{constructor(e){super("BackgroundEvent",S.Error),this.privError=e}get error(){return this.privError}}class C{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(C.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(C.throwIfNullOrUndefined(e,t),e.length===0)throw new Error("throwIfArrayEmptyOrWhitespace:"+t);for(const r of e)C.throwIfNullOrWhitespace(r,t)}static throwIfFileDoesNotExist(e,t){C.throwIfNullOrWhitespace(e,t)}static throwIfNotUndefined(e,t){if(e!==void 0)throw new Error("throwIfNotUndefined:"+t)}}class y{}y.AuthKey="Ocp-Apim-Subscription-Key",y.ConnectionId="X-ConnectionId",y.ContentType="Content-Type",y.CustomCommandsAppId="X-CommandsAppId",y.Path="Path",y.RequestId="X-RequestId",y.RequestStreamId="X-StreamId",y.RequestTimestamp="X-Timestamp";class Le{constructor(e,t){this.privHeaderName=e,this.privToken=t}get headerName(){return this.privHeaderName}get token(){return this.privToken}}class ii{constructor(e){if(!e)throw new k("subscriptionKey");this.privAuthInfo=new Le(y.AuthKey,e)}fetch(e){return Promise.resolve(this.privAuthInfo)}fetchOnExpiry(e){return Promise.resolve(this.privAuthInfo)}}const ot="Authorization";class ue{constructor(e,t){if(!e)throw new k("fetchCallback");if(!t)throw new k("fetchOnExpiryCallback");this.privFetchCallback=e,this.privFetchOnExpiryCallback=t}fetch(e){return this.privFetchCallback(e).then(t=>new Le(ot,ue.privTokenPrefix+t))}fetchOnExpiry(e){return this.privFetchOnExpiryCallback(e).then(t=>new Le(ot,ue.privTokenPrefix+t))}}ue.privTokenPrefix="bearer ";class at{constructor(e){C.throwIfNullOrUndefined(void 0,`
2
- File System access not available, please use Push or PullAudioOutputStream`),this.privFd=(void 0)(e,"w")}set format(e){C.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){C.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(i){i[i.PCM=1]="PCM",i[i.MuLaw=2]="MuLaw",i[i.Siren=3]="Siren",i[i.MP3=4]="MP3",i[i.SILKSkype=5]="SILKSkype",i[i.OGG_OPUS=6]="OGG_OPUS",i[i.WEBM_OPUS=7]="WEBM_OPUS",i[i.ALaw=8]="ALaw",i[i.FLAC=9]="FLAC",i[i.OPUS=10]="OPUS"})(v||(v={}));class ge{static getDefaultInputFormat(){return H.getDefaultInputFormat()}static getWaveFormat(e,t,r,n){return new H(e,t,r,n)}static getWaveFormatPCM(e,t,r){return new H(e,t,r)}}class H extends ge{constructor(e=16e3,t=16,r=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=r,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 H}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,r){for(let n=0;n<r.length;n++)e.setUint8(t+n,r.charCodeAt(n))}}var Oe=globalThis&&globalThis.__awaiter||function(i,e,t,r){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(r.next(c))}catch(p){o(p)}}function u(c){try{h(r.throw(c))}catch(p){o(p)}}function h(c){c.done?s(c.value):n(c.value).then(a,u)}h((r=r.apply(i,e||[])).next())})};class _e{constructor(){}static createPushStream(e){return ct.create(e)}static createPullStream(e,t){return ht.create(e,t)}}class ct extends _e{static create(e){return new ri(e)}}class ri extends ct{constructor(e){super(),e===void 0?this.privFormat=H.getDefaultInputFormat():this.privFormat=e,this.privEvents=new U,this.privId=E(),this.privStream=new Ne(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 r=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(r)):(typeof Blob!="undefined"?t.push(s.buffer):r=Buffer.concat([r,this.toBuffer(s.buffer)]),n()));return n()})}turnOn(){this.onEvent(new le(this.privId)),this.onEvent(new oe(this.privId))}attach(e){return Oe(this,void 0,void 0,function*(){this.onEvent(new me(this.privId,e)),yield this.turnOn();const t=this.privStream;return this.onEvent(new Se(this.privId,e)),{detach:()=>Oe(this,void 0,void 0,function*(){return this.onEvent(new K(this.privId,e)),this.turnOff()}),id:()=>e,read:()=>t.read()}})}detach(e){this.onEvent(new K(this.privId,e))}turnOff(){}get events(){return this.privEvents}get deviceInfo(){return Promise.resolve({bitspersample:this.privFormat.bitsPerSample,channelcount:this.privFormat.channels,connectivity:ie.Unknown,manufacturer:"Speech SDK",model:"PushStream",samplerate:this.privFormat.samplesPerSec,type:re.Stream})}onEvent(e){this.privEvents.onEvent(e),M.instance.onEvent(e)}toBuffer(e){const t=Buffer.alloc(e.byteLength),r=new Uint8Array(e);for(let n=0;n<t.length;++n)t[n]=r[n];return t}}class ht extends _e{constructor(){super()}static create(e,t){return new ut(e,t)}}class ut extends ht{constructor(e,t){super(),t===void 0?this.privFormat=ge.getDefaultInputFormat():this.privFormat=t,this.privEvents=new U,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 le(this.privId)),this.onEvent(new oe(this.privId))}attach(e){return Oe(this,void 0,void 0,function*(){return this.onEvent(new me(this.privId,e)),yield this.turnOn(),this.onEvent(new Se(this.privId,e)),{detach:()=>(this.privCallback.close(),this.onEvent(new K(this.privId,e)),this.turnOff()),id:()=>e,read:()=>{let t=0,r;for(;t<this.privBufferSize;){const n=new ArrayBuffer(this.privBufferSize-t),s=this.privCallback.read(n);if(r===void 0?r=n:new Int8Array(r).set(new Int8Array(n),t),s===0)break;t+=s}return Promise.resolve({buffer:r.slice(0,t),isEnd:this.privIsClosed||t===0,timeReceived:Date.now()})}}})}detach(e){this.onEvent(new K(this.privId,e))}turnOff(){}get events(){return this.privEvents}get deviceInfo(){return Promise.resolve({bitspersample:this.privFormat.bitsPerSample,channelcount:this.privFormat.channels,connectivity:ie.Unknown,manufacturer:"Speech SDK",model:"PullStream",samplerate:this.privFormat.samplesPerSec,type:re.Stream})}onEvent(e){this.privEvents.onEvent(e),M.instance.onEvent(e)}}var f;(function(i){i[i.Raw8Khz8BitMonoMULaw=0]="Raw8Khz8BitMonoMULaw",i[i.Riff16Khz16KbpsMonoSiren=1]="Riff16Khz16KbpsMonoSiren",i[i.Audio16Khz16KbpsMonoSiren=2]="Audio16Khz16KbpsMonoSiren",i[i.Audio16Khz32KBitRateMonoMp3=3]="Audio16Khz32KBitRateMonoMp3",i[i.Audio16Khz128KBitRateMonoMp3=4]="Audio16Khz128KBitRateMonoMp3",i[i.Audio16Khz64KBitRateMonoMp3=5]="Audio16Khz64KBitRateMonoMp3",i[i.Audio24Khz48KBitRateMonoMp3=6]="Audio24Khz48KBitRateMonoMp3",i[i.Audio24Khz96KBitRateMonoMp3=7]="Audio24Khz96KBitRateMonoMp3",i[i.Audio24Khz160KBitRateMonoMp3=8]="Audio24Khz160KBitRateMonoMp3",i[i.Raw16Khz16BitMonoTrueSilk=9]="Raw16Khz16BitMonoTrueSilk",i[i.Riff16Khz16BitMonoPcm=10]="Riff16Khz16BitMonoPcm",i[i.Riff8Khz16BitMonoPcm=11]="Riff8Khz16BitMonoPcm",i[i.Riff24Khz16BitMonoPcm=12]="Riff24Khz16BitMonoPcm",i[i.Riff8Khz8BitMonoMULaw=13]="Riff8Khz8BitMonoMULaw",i[i.Raw16Khz16BitMonoPcm=14]="Raw16Khz16BitMonoPcm",i[i.Raw24Khz16BitMonoPcm=15]="Raw24Khz16BitMonoPcm",i[i.Raw8Khz16BitMonoPcm=16]="Raw8Khz16BitMonoPcm",i[i.Ogg16Khz16BitMonoOpus=17]="Ogg16Khz16BitMonoOpus",i[i.Ogg24Khz16BitMonoOpus=18]="Ogg24Khz16BitMonoOpus",i[i.Raw48Khz16BitMonoPcm=19]="Raw48Khz16BitMonoPcm",i[i.Riff48Khz16BitMonoPcm=20]="Riff48Khz16BitMonoPcm",i[i.Audio48Khz96KBitRateMonoMp3=21]="Audio48Khz96KBitRateMonoMp3",i[i.Audio48Khz192KBitRateMonoMp3=22]="Audio48Khz192KBitRateMonoMp3",i[i.Ogg48Khz16BitMonoOpus=23]="Ogg48Khz16BitMonoOpus",i[i.Webm16Khz16BitMonoOpus=24]="Webm16Khz16BitMonoOpus",i[i.Webm24Khz16BitMonoOpus=25]="Webm24Khz16BitMonoOpus",i[i.Raw24Khz16BitMonoTrueSilk=26]="Raw24Khz16BitMonoTrueSilk",i[i.Raw8Khz8BitMonoALaw=27]="Raw8Khz8BitMonoALaw",i[i.Riff8Khz8BitMonoALaw=28]="Riff8Khz8BitMonoALaw",i[i.Webm24Khz16Bit24KbpsMonoOpus=29]="Webm24Khz16Bit24KbpsMonoOpus",i[i.Audio16Khz16Bit32KbpsMonoOpus=30]="Audio16Khz16Bit32KbpsMonoOpus",i[i.Audio24Khz16Bit48KbpsMonoOpus=31]="Audio24Khz16Bit48KbpsMonoOpus",i[i.Audio24Khz16Bit24KbpsMonoOpus=32]="Audio24Khz16Bit24KbpsMonoOpus",i[i.Raw22050Hz16BitMonoPcm=33]="Raw22050Hz16BitMonoPcm",i[i.Riff22050Hz16BitMonoPcm=34]="Riff22050Hz16BitMonoPcm",i[i.Raw44100Hz16BitMonoPcm=35]="Raw44100Hz16BitMonoPcm",i[i.Riff44100Hz16BitMonoPcm=36]="Riff44100Hz16BitMonoPcm"})(f||(f={}));class l extends H{constructor(e,t,r,n,s,o,a,u,h){super(r,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?l.getDefaultOutputFormat():l.fromSpeechSynthesisOutputFormatString(l.SpeechSynthesisOutputFormatToString[e])}static fromSpeechSynthesisOutputFormatString(e){switch(e){case"raw-8khz-8bit-mono-mulaw":return new l(v.MuLaw,1,8e3,8e3,1,8,e,e,!1);case"riff-16khz-16kbps-mono-siren":return new l(v.Siren,1,16e3,2e3,40,0,e,"audio-16khz-16kbps-mono-siren",!0);case"audio-16khz-16kbps-mono-siren":return new l(v.Siren,1,16e3,2e3,40,0,e,e,!1);case"audio-16khz-32kbitrate-mono-mp3":return new l(v.MP3,1,16e3,32<<7,2,16,e,e,!1);case"audio-16khz-128kbitrate-mono-mp3":return new l(v.MP3,1,16e3,128<<7,2,16,e,e,!1);case"audio-16khz-64kbitrate-mono-mp3":return new l(v.MP3,1,16e3,64<<7,2,16,e,e,!1);case"audio-24khz-48kbitrate-mono-mp3":return new l(v.MP3,1,24e3,48<<7,2,16,e,e,!1);case"audio-24khz-96kbitrate-mono-mp3":return new l(v.MP3,1,24e3,96<<7,2,16,e,e,!1);case"audio-24khz-160kbitrate-mono-mp3":return new l(v.MP3,1,24e3,160<<7,2,16,e,e,!1);case"raw-16khz-16bit-mono-truesilk":return new l(v.SILKSkype,1,16e3,32e3,2,16,e,e,!1);case"riff-8khz-16bit-mono-pcm":return new l(v.PCM,1,8e3,16e3,2,16,e,"raw-8khz-16bit-mono-pcm",!0);case"riff-24khz-16bit-mono-pcm":return new l(v.PCM,1,24e3,48e3,2,16,e,"raw-24khz-16bit-mono-pcm",!0);case"riff-8khz-8bit-mono-mulaw":return new l(v.MuLaw,1,8e3,8e3,1,8,e,"raw-8khz-8bit-mono-mulaw",!0);case"raw-16khz-16bit-mono-pcm":return new l(v.PCM,1,16e3,32e3,2,16,e,"raw-16khz-16bit-mono-pcm",!1);case"raw-24khz-16bit-mono-pcm":return new l(v.PCM,1,24e3,48e3,2,16,e,"raw-24khz-16bit-mono-pcm",!1);case"raw-8khz-16bit-mono-pcm":return new l(v.PCM,1,8e3,16e3,2,16,e,"raw-8khz-16bit-mono-pcm",!1);case"ogg-16khz-16bit-mono-opus":return new l(v.OGG_OPUS,1,16e3,8192,2,16,e,e,!1);case"ogg-24khz-16bit-mono-opus":return new l(v.OGG_OPUS,1,24e3,8192,2,16,e,e,!1);case"raw-48khz-16bit-mono-pcm":return new l(v.PCM,1,48e3,96e3,2,16,e,"raw-48khz-16bit-mono-pcm",!1);case"riff-48khz-16bit-mono-pcm":return new l(v.PCM,1,48e3,96e3,2,16,e,"raw-48khz-16bit-mono-pcm",!0);case"audio-48khz-96kbitrate-mono-mp3":return new l(v.MP3,1,48e3,96<<7,2,16,e,e,!1);case"audio-48khz-192kbitrate-mono-mp3":return new l(v.MP3,1,48e3,192<<7,2,16,e,e,!1);case"ogg-48khz-16bit-mono-opus":return new l(v.OGG_OPUS,1,48e3,12e3,2,16,e,e,!1);case"webm-16khz-16bit-mono-opus":return new l(v.WEBM_OPUS,1,16e3,4e3,2,16,e,e,!1);case"webm-24khz-16bit-mono-opus":return new l(v.WEBM_OPUS,1,24e3,6e3,2,16,e,e,!1);case"webm-24khz-16bit-24kbps-mono-opus":return new l(v.WEBM_OPUS,1,24e3,3e3,2,16,e,e,!1);case"audio-16khz-16bit-32kbps-mono-opus":return new l(v.OPUS,1,16e3,4e3,2,16,e,e,!1);case"audio-24khz-16bit-48kbps-mono-opus":return new l(v.OPUS,1,24e3,6e3,2,16,e,e,!1);case"audio-24khz-16bit-24kbps-mono-opus":return new l(v.OPUS,1,24e3,3e3,2,16,e,e,!1);case"audio-24khz-16bit-mono-flac":return new l(v.FLAC,1,24e3,24e3,2,16,e,e,!1);case"audio-48khz-16bit-mono-flac":return new l(v.FLAC,1,48e3,3e4,2,16,e,e,!1);case"raw-24khz-16bit-mono-truesilk":return new l(v.SILKSkype,1,24e3,48e3,2,16,e,e,!1);case"raw-8khz-8bit-mono-alaw":return new l(v.ALaw,1,8e3,8e3,1,8,e,e,!1);case"riff-8khz-8bit-mono-alaw":return new l(v.ALaw,1,8e3,8e3,1,8,e,"raw-8khz-8bit-mono-alaw",!0);case"raw-22050hz-16bit-mono-pcm":return new l(v.PCM,1,22050,44100,2,16,e,e,!1);case"riff-22050hz-16bit-mono-pcm":return new l(v.PCM,1,22050,44100,2,16,e,"raw-22050hz-16bit-mono-pcm",!0);case"raw-44100hz-16bit-mono-pcm":return new l(v.PCM,1,44100,88200,2,16,e,e,!1);case"riff-44100hz-16bit-mono-pcm":return new l(v.PCM,1,44100,88200,2,16,e,"raw-44100hz-16bit-mono-pcm",!0);case"riff-16khz-16bit-mono-pcm":default:return new l(v.PCM,1,16e3,32e3,2,16,"riff-16khz-16bit-mono-pcm","raw-16khz-16bit-mono-pcm",!0)}}static getDefaultOutputFormat(){return l.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}}l.SpeechSynthesisOutputFormatToString={[f.Raw8Khz8BitMonoMULaw]:"raw-8khz-8bit-mono-mulaw",[f.Riff16Khz16KbpsMonoSiren]:"riff-16khz-16kbps-mono-siren",[f.Audio16Khz16KbpsMonoSiren]:"audio-16khz-16kbps-mono-siren",[f.Audio16Khz32KBitRateMonoMp3]:"audio-16khz-32kbitrate-mono-mp3",[f.Audio16Khz128KBitRateMonoMp3]:"audio-16khz-128kbitrate-mono-mp3",[f.Audio16Khz64KBitRateMonoMp3]:"audio-16khz-64kbitrate-mono-mp3",[f.Audio24Khz48KBitRateMonoMp3]:"audio-24khz-48kbitrate-mono-mp3",[f.Audio24Khz96KBitRateMonoMp3]:"audio-24khz-96kbitrate-mono-mp3",[f.Audio24Khz160KBitRateMonoMp3]:"audio-24khz-160kbitrate-mono-mp3",[f.Raw16Khz16BitMonoTrueSilk]:"raw-16khz-16bit-mono-truesilk",[f.Riff16Khz16BitMonoPcm]:"riff-16khz-16bit-mono-pcm",[f.Riff8Khz16BitMonoPcm]:"riff-8khz-16bit-mono-pcm",[f.Riff24Khz16BitMonoPcm]:"riff-24khz-16bit-mono-pcm",[f.Riff8Khz8BitMonoMULaw]:"riff-8khz-8bit-mono-mulaw",[f.Raw16Khz16BitMonoPcm]:"raw-16khz-16bit-mono-pcm",[f.Raw24Khz16BitMonoPcm]:"raw-24khz-16bit-mono-pcm",[f.Raw8Khz16BitMonoPcm]:"raw-8khz-16bit-mono-pcm",[f.Ogg16Khz16BitMonoOpus]:"ogg-16khz-16bit-mono-opus",[f.Ogg24Khz16BitMonoOpus]:"ogg-24khz-16bit-mono-opus",[f.Raw48Khz16BitMonoPcm]:"raw-48khz-16bit-mono-pcm",[f.Riff48Khz16BitMonoPcm]:"riff-48khz-16bit-mono-pcm",[f.Audio48Khz96KBitRateMonoMp3]:"audio-48khz-96kbitrate-mono-mp3",[f.Audio48Khz192KBitRateMonoMp3]:"audio-48khz-192kbitrate-mono-mp3",[f.Ogg48Khz16BitMonoOpus]:"ogg-48khz-16bit-mono-opus",[f.Webm16Khz16BitMonoOpus]:"webm-16khz-16bit-mono-opus",[f.Webm24Khz16BitMonoOpus]:"webm-24khz-16bit-mono-opus",[f.Webm24Khz16Bit24KbpsMonoOpus]:"webm-24khz-16bit-24kbps-mono-opus",[f.Raw24Khz16BitMonoTrueSilk]:"raw-24khz-16bit-mono-truesilk",[f.Raw8Khz8BitMonoALaw]:"raw-8khz-8bit-mono-alaw",[f.Riff8Khz8BitMonoALaw]:"riff-8khz-8bit-mono-alaw",[f.Audio16Khz16Bit32KbpsMonoOpus]:"audio-16khz-16bit-32kbps-mono-opus",[f.Audio24Khz16Bit48KbpsMonoOpus]:"audio-24khz-16bit-48kbps-mono-opus",[f.Audio24Khz16Bit24KbpsMonoOpus]:"audio-24khz-16bit-24kbps-mono-opus",[f.Raw22050Hz16BitMonoPcm]:"raw-22050hz-16bit-mono-pcm",[f.Riff22050Hz16BitMonoPcm]:"riff-22050hz-16bit-mono-pcm",[f.Raw44100Hz16BitMonoPcm]:"raw-44100hz-16bit-mono-pcm",[f.Riff44100Hz16BitMonoPcm]:"riff-44100hz-16bit-mono-pcm"};var ni=globalThis&&globalThis.__awaiter||function(i,e,t,r){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(r.next(c))}catch(p){o(p)}}function u(c){try{h(r.throw(c))}catch(p){o(p)}}function h(c){c.done?s(c.value):n(c.value).then(a,u)}h((r=r.apply(i,e||[])).next())})};class pt{constructor(){}static createPullStream(){return Ce.create()}}class Ce extends pt{static create(){return new Ke}}class Ke extends Ce{constructor(){super(),this.privId=E(),this.privStream=new nt}set format(e){e==null&&(this.privFormat=l.getDefaultOutputFormat()),this.privFormat=e}get format(){return this.privFormat}get isClosed(){return this.privStream.isClosed}id(){return this.privId}read(e){return ni(this,void 0,void 0,function*(){const t=new Int8Array(e);let r=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),r=this.privLastChunkView.length,this.privLastChunkView=void 0}for(;r<e.byteLength&&!this.privStream.isReadEnded;){const n=yield this.privStream.read();if(n!==void 0&&!n.isEnd){let s;n.buffer.byteLength>e.byteLength-r?(s=n.buffer.slice(0,e.byteLength-r),this.privLastChunkView=new Int8Array(n.buffer.slice(e.byteLength-r))):s=n.buffer,t.set(new Int8Array(s),r),r+=s.byteLength}else this.privStream.readEnded()}return r})}write(e){C.throwIfNullOrUndefined(this.privStream,"must set format before writing"),this.privStream.writeStreamChunk({buffer:e,isEnd:!1,timeReceived:Date.now()})}close(){this.privStream.close()}}class dt extends pt{constructor(){super()}static create(e){return new Ue(e)}}class Ue extends dt{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 Q{static fromDefaultMicrophoneInput(){const e=new Qe(!0);return new X(new N(e))}static fromMicrophoneInput(e){const t=new Qe(!0);return new X(new N(t,e))}static fromWavFileInput(e,t="unnamedBuffer.wav"){return new X(new Mi(e,t))}static fromStreamInput(e){if(e instanceof si)return new X(new ut(e));if(e instanceof _e)return new X(e);if(typeof MediaStream!="undefined"&&e instanceof MediaStream){const t=new Qe(!1);return new X(new N(t,null,null,e))}throw new Error("Not Supported Type")}static fromDefaultSpeakerOutput(){return new Z(new Ve)}static fromSpeakerOutput(e){if(e===void 0)return Q.fromDefaultSpeakerOutput();if(e instanceof Ve)return new Z(e);throw new Error("Not Supported Type")}static fromAudioFileOutput(e){return new Z(new at(e))}static fromStreamOutput(e){if(e instanceof vt)return new Z(new Ue(e));if(e instanceof dt)return new Z(e);if(e instanceof Ce)return new Z(e);throw new Error("Not Supported Type")}}class X extends Q{constructor(e){super(),this.privSource=e}get format(){return this.privSource.format}close(e,t){this.privSource.turnOff().then(()=>{e&&e()},r=>{t&&t(r)})}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(C.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 Z extends Q{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 ye;(function(i){i[i.Error=0]="Error",i[i.EndOfStream=1]="EndOfStream"})(ye||(ye={}));class si{}class vt{}var pe;(function(i){i[i.Simple=0]="Simple",i[i.Detailed=1]="Detailed"})(pe||(pe={}));var W;(function(i){i[i.NoMatch=0]="NoMatch",i[i.Canceled=1]="Canceled",i[i.RecognizingSpeech=2]="RecognizingSpeech",i[i.RecognizedSpeech=3]="RecognizedSpeech",i[i.RecognizedKeyword=4]="RecognizedKeyword",i[i.RecognizingIntent=5]="RecognizingIntent",i[i.RecognizedIntent=6]="RecognizedIntent",i[i.TranslatingSpeech=7]="TranslatingSpeech",i[i.TranslatedSpeech=8]="TranslatedSpeech",i[i.SynthesizingAudio=9]="SynthesizingAudio",i[i.SynthesizingAudioCompleted=10]="SynthesizingAudioCompleted",i[i.SynthesizingAudioStarted=11]="SynthesizingAudioStarted",i[i.EnrollingVoiceProfile=12]="EnrollingVoiceProfile",i[i.EnrolledVoiceProfile=13]="EnrolledVoiceProfile",i[i.RecognizedSpeakers=14]="RecognizedSpeakers",i[i.RecognizedSpeaker=15]="RecognizedSpeaker",i[i.ResetVoiceProfile=16]="ResetVoiceProfile",i[i.DeletedVoiceProfile=17]="DeletedVoiceProfile",i[i.VoicesListRetrieved=18]="VoicesListRetrieved"})(W||(W={}));class lt{constructor(){}static fromSubscription(e,t){C.throwIfNullOrWhitespace(e,"subscriptionKey"),C.throwIfNullOrWhitespace(t,"region");const r=new Y;return r.setProperty(d.SpeechServiceConnection_Region,t),r.setProperty(d.SpeechServiceConnection_IntentRegion,t),r.setProperty(d.SpeechServiceConnection_Key,e),r}static fromEndpoint(e,t){C.throwIfNull(e,"endpoint");const r=new Y;return r.setProperty(d.SpeechServiceConnection_Endpoint,e.href),t!==void 0&&r.setProperty(d.SpeechServiceConnection_Key,t),r}static fromHost(e,t){C.throwIfNull(e,"hostName");const r=new Y;return r.setProperty(d.SpeechServiceConnection_Host,e.protocol+"//"+e.hostname+(e.port===""?"":":"+e.port)),t!==void 0&&r.setProperty(d.SpeechServiceConnection_Key,t),r}static fromAuthorizationToken(e,t){C.throwIfNull(e,"authorizationToken"),C.throwIfNullOrWhitespace(t,"region");const r=new Y;return r.setProperty(d.SpeechServiceConnection_Region,t),r.setProperty(d.SpeechServiceConnection_IntentRegion,t),r.authorizationToken=e,r}close(){}}class Y extends lt{constructor(){super(),this.privProperties=new ee,this.speechRecognitionLanguage="en-US",this.outputFormat=pe.Simple}get properties(){return this.privProperties}get endPoint(){return new URL(this.privProperties.getProperty(d.SpeechServiceConnection_Endpoint))}get subscriptionKey(){return this.privProperties.getProperty(d.SpeechServiceConnection_Key)}get region(){return this.privProperties.getProperty(d.SpeechServiceConnection_Region)}get authorizationToken(){return this.privProperties.getProperty(d.SpeechServiceAuthorization_Token)}set authorizationToken(e){this.privProperties.setProperty(d.SpeechServiceAuthorization_Token,e)}get speechRecognitionLanguage(){return this.privProperties.getProperty(d.SpeechServiceConnection_RecoLanguage)}set speechRecognitionLanguage(e){this.privProperties.setProperty(d.SpeechServiceConnection_RecoLanguage,e)}get autoDetectSourceLanguages(){return this.privProperties.getProperty(d.SpeechServiceConnection_AutoDetectSourceLanguages)}set autoDetectSourceLanguages(e){this.privProperties.setProperty(d.SpeechServiceConnection_AutoDetectSourceLanguages,e)}get outputFormat(){return pe[this.privProperties.getProperty(At,void 0)]}set outputFormat(e){this.privProperties.setProperty(At,pe[e])}get endpointId(){return this.privProperties.getProperty(d.SpeechServiceConnection_EndpointId)}set endpointId(e){this.privProperties.setProperty(d.SpeechServiceConnection_EndpointId,e)}setProperty(e,t){C.throwIfNull(t,"value"),this.privProperties.setProperty(e,t)}getProperty(e,t){return this.privProperties.getProperty(e,t)}setProxy(e,t,r,n){this.setProperty(d[d.SpeechServiceConnection_ProxyHostName],e),this.setProperty(d[d.SpeechServiceConnection_ProxyPort],t),this.setProperty(d[d.SpeechServiceConnection_ProxyUserName],r),this.setProperty(d[d.SpeechServiceConnection_ProxyPassword],n)}setServiceProperty(e,t){const r=JSON.parse(this.privProperties.getProperty(Fe,"{}"));r[e]=t,this.privProperties.setProperty(Fe,JSON.stringify(r))}setProfanity(e){this.privProperties.setProperty(d.SpeechServiceResponse_ProfanityOption,He[e])}enableAudioLogging(){this.privProperties.setProperty(d.SpeechServiceConnection_EnableAudioLogging,"true")}requestWordLevelTimestamps(){this.privProperties.setProperty(d.SpeechServiceResponse_RequestWordLevelTimestamps,"true")}enableDictation(){this.privProperties.setProperty(Ai,"true")}clone(){const e=new Y;return e.privProperties=this.privProperties.clone(),e}get speechSynthesisLanguage(){return this.privProperties.getProperty(d.SpeechServiceConnection_SynthLanguage)}set speechSynthesisLanguage(e){this.privProperties.setProperty(d.SpeechServiceConnection_SynthLanguage,e)}get speechSynthesisVoiceName(){return this.privProperties.getProperty(d.SpeechServiceConnection_SynthVoice)}set speechSynthesisVoiceName(e){this.privProperties.setProperty(d.SpeechServiceConnection_SynthVoice,e)}get speechSynthesisOutputFormat(){return f[this.privProperties.getProperty(d.SpeechServiceConnection_SynthOutputFormat,void 0)]}set speechSynthesisOutputFormat(e){this.privProperties.setProperty(d.SpeechServiceConnection_SynthOutputFormat,f[e])}}class ee{constructor(){this.privKeys=[],this.privValues=[]}getProperty(e,t){let r;typeof e=="string"?r=e:r=d[e];for(let n=0;n<this.privKeys.length;n++)if(this.privKeys[n]===r)return this.privValues[n];if(t!==void 0)return String(t)}setProperty(e,t){let r;typeof e=="string"?r=e:r=d[e];for(let n=0;n<this.privKeys.length;n++)if(this.privKeys[n]===r){this.privValues[n]=t;return}this.privKeys.push(r),this.privValues.push(t)}clone(){const e=new ee;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 r=this.getProperty(t);e.setProperty(t,r)}})}get keys(){return this.privKeys}}var d;(function(i){i[i.SpeechServiceConnection_Key=0]="SpeechServiceConnection_Key",i[i.SpeechServiceConnection_Endpoint=1]="SpeechServiceConnection_Endpoint",i[i.SpeechServiceConnection_Region=2]="SpeechServiceConnection_Region",i[i.SpeechServiceAuthorization_Token=3]="SpeechServiceAuthorization_Token",i[i.SpeechServiceAuthorization_Type=4]="SpeechServiceAuthorization_Type",i[i.SpeechServiceConnection_EndpointId=5]="SpeechServiceConnection_EndpointId",i[i.SpeechServiceConnection_TranslationToLanguages=6]="SpeechServiceConnection_TranslationToLanguages",i[i.SpeechServiceConnection_TranslationVoice=7]="SpeechServiceConnection_TranslationVoice",i[i.SpeechServiceConnection_TranslationFeatures=8]="SpeechServiceConnection_TranslationFeatures",i[i.SpeechServiceConnection_IntentRegion=9]="SpeechServiceConnection_IntentRegion",i[i.SpeechServiceConnection_ProxyHostName=10]="SpeechServiceConnection_ProxyHostName",i[i.SpeechServiceConnection_ProxyPort=11]="SpeechServiceConnection_ProxyPort",i[i.SpeechServiceConnection_ProxyUserName=12]="SpeechServiceConnection_ProxyUserName",i[i.SpeechServiceConnection_ProxyPassword=13]="SpeechServiceConnection_ProxyPassword",i[i.SpeechServiceConnection_RecoMode=14]="SpeechServiceConnection_RecoMode",i[i.SpeechServiceConnection_RecoLanguage=15]="SpeechServiceConnection_RecoLanguage",i[i.Speech_SessionId=16]="Speech_SessionId",i[i.SpeechServiceConnection_SynthLanguage=17]="SpeechServiceConnection_SynthLanguage",i[i.SpeechServiceConnection_SynthVoice=18]="SpeechServiceConnection_SynthVoice",i[i.SpeechServiceConnection_SynthOutputFormat=19]="SpeechServiceConnection_SynthOutputFormat",i[i.SpeechServiceConnection_AutoDetectSourceLanguages=20]="SpeechServiceConnection_AutoDetectSourceLanguages",i[i.SpeechServiceResponse_RequestDetailedResultTrueFalse=21]="SpeechServiceResponse_RequestDetailedResultTrueFalse",i[i.SpeechServiceResponse_RequestProfanityFilterTrueFalse=22]="SpeechServiceResponse_RequestProfanityFilterTrueFalse",i[i.SpeechServiceResponse_JsonResult=23]="SpeechServiceResponse_JsonResult",i[i.SpeechServiceResponse_JsonErrorDetails=24]="SpeechServiceResponse_JsonErrorDetails",i[i.CancellationDetails_Reason=25]="CancellationDetails_Reason",i[i.CancellationDetails_ReasonText=26]="CancellationDetails_ReasonText",i[i.CancellationDetails_ReasonDetailedText=27]="CancellationDetails_ReasonDetailedText",i[i.LanguageUnderstandingServiceResponse_JsonResult=28]="LanguageUnderstandingServiceResponse_JsonResult",i[i.SpeechServiceConnection_Url=29]="SpeechServiceConnection_Url",i[i.SpeechServiceConnection_InitialSilenceTimeoutMs=30]="SpeechServiceConnection_InitialSilenceTimeoutMs",i[i.SpeechServiceConnection_EndSilenceTimeoutMs=31]="SpeechServiceConnection_EndSilenceTimeoutMs",i[i.Speech_SegmentationSilenceTimeoutMs=32]="Speech_SegmentationSilenceTimeoutMs",i[i.SpeechServiceConnection_EnableAudioLogging=33]="SpeechServiceConnection_EnableAudioLogging",i[i.SpeechServiceConnection_AtStartLanguageIdPriority=34]="SpeechServiceConnection_AtStartLanguageIdPriority",i[i.SpeechServiceConnection_ContinuousLanguageIdPriority=35]="SpeechServiceConnection_ContinuousLanguageIdPriority",i[i.SpeechServiceConnection_RecognitionEndpointVersion=36]="SpeechServiceConnection_RecognitionEndpointVersion",i[i.SpeechServiceResponse_ProfanityOption=37]="SpeechServiceResponse_ProfanityOption",i[i.SpeechServiceResponse_PostProcessingOption=38]="SpeechServiceResponse_PostProcessingOption",i[i.SpeechServiceResponse_RequestWordLevelTimestamps=39]="SpeechServiceResponse_RequestWordLevelTimestamps",i[i.SpeechServiceResponse_StablePartialResultThreshold=40]="SpeechServiceResponse_StablePartialResultThreshold",i[i.SpeechServiceResponse_OutputFormatOption=41]="SpeechServiceResponse_OutputFormatOption",i[i.SpeechServiceResponse_TranslationRequestStablePartialResult=42]="SpeechServiceResponse_TranslationRequestStablePartialResult",i[i.SpeechServiceResponse_RequestWordBoundary=43]="SpeechServiceResponse_RequestWordBoundary",i[i.SpeechServiceResponse_RequestPunctuationBoundary=44]="SpeechServiceResponse_RequestPunctuationBoundary",i[i.SpeechServiceResponse_RequestSentenceBoundary=45]="SpeechServiceResponse_RequestSentenceBoundary",i[i.Conversation_ApplicationId=46]="Conversation_ApplicationId",i[i.Conversation_DialogType=47]="Conversation_DialogType",i[i.Conversation_Initial_Silence_Timeout=48]="Conversation_Initial_Silence_Timeout",i[i.Conversation_From_Id=49]="Conversation_From_Id",i[i.Conversation_Conversation_Id=50]="Conversation_Conversation_Id",i[i.Conversation_Custom_Voice_Deployment_Ids=51]="Conversation_Custom_Voice_Deployment_Ids",i[i.Conversation_Speech_Activity_Template=52]="Conversation_Speech_Activity_Template",i[i.Conversation_Request_Bot_Status_Messages=53]="Conversation_Request_Bot_Status_Messages",i[i.Conversation_Agent_Connection_Id=54]="Conversation_Agent_Connection_Id",i[i.SpeechServiceConnection_Host=55]="SpeechServiceConnection_Host",i[i.ConversationTranslator_Host=56]="ConversationTranslator_Host",i[i.ConversationTranslator_Name=57]="ConversationTranslator_Name",i[i.ConversationTranslator_CorrelationId=58]="ConversationTranslator_CorrelationId",i[i.ConversationTranslator_Token=59]="ConversationTranslator_Token",i[i.PronunciationAssessment_ReferenceText=60]="PronunciationAssessment_ReferenceText",i[i.PronunciationAssessment_GradingSystem=61]="PronunciationAssessment_GradingSystem",i[i.PronunciationAssessment_Granularity=62]="PronunciationAssessment_Granularity",i[i.PronunciationAssessment_EnableMiscue=63]="PronunciationAssessment_EnableMiscue",i[i.PronunciationAssessment_Json=64]="PronunciationAssessment_Json",i[i.PronunciationAssessment_Params=65]="PronunciationAssessment_Params",i[i.SpeakerRecognition_Api_Version=66]="SpeakerRecognition_Api_Version"})(d||(d={}));var te;(function(i){i[i.NoError=0]="NoError",i[i.AuthenticationFailure=1]="AuthenticationFailure",i[i.BadRequestParameters=2]="BadRequestParameters",i[i.TooManyRequests=3]="TooManyRequests",i[i.ConnectionFailure=4]="ConnectionFailure",i[i.ServiceTimeout=5]="ServiceTimeout",i[i.ServiceError=6]="ServiceError",i[i.RuntimeError=7]="RuntimeError",i[i.Forbidden=8]="Forbidden"})(te||(te={}));class m{}m.BotId="botid",m.CustomSpeechDeploymentId="cid",m.CustomVoiceDeploymentId="deploymentId",m.EnableAudioLogging="storeAudio",m.EnableLanguageId="lidEnabled",m.EnableWordLevelTimestamps="wordLevelTimestamps",m.EndSilenceTimeoutMs="endSilenceTimeoutMs",m.SegmentationSilenceTimeoutMs="segmentationSilenceTimeoutMs",m.Format="format",m.InitialSilenceTimeoutMs="initialSilenceTimeoutMs",m.Language="language",m.Profanity="profanity",m.RequestBotStatusMessages="enableBotMessageStatus",m.StableIntermediateThreshold="stableIntermediateThreshold",m.StableTranslation="stableTranslation",m.TestHooks="testhooks",m.Postprocessing="postprocessing";class ft{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,r){new Map([[d.Speech_SegmentationSilenceTimeoutMs,m.SegmentationSilenceTimeoutMs],[d.SpeechServiceConnection_EnableAudioLogging,m.EnableAudioLogging],[d.SpeechServiceConnection_EndSilenceTimeoutMs,m.EndSilenceTimeoutMs],[d.SpeechServiceConnection_InitialSilenceTimeoutMs,m.InitialSilenceTimeoutMs],[d.SpeechServiceResponse_PostProcessingOption,m.Postprocessing],[d.SpeechServiceResponse_ProfanityOption,m.Profanity],[d.SpeechServiceResponse_RequestWordLevelTimestamps,m.EnableWordLevelTimestamps],[d.SpeechServiceResponse_StablePartialResultThreshold,m.StableIntermediateThreshold]]).forEach((o,a)=>{this.setUrlParameter(a,o,e,t,r)});const s=JSON.parse(e.parameters.getProperty(Fe,"{}"));Object.keys(s).forEach(o=>{t[o]=s[o]})}setUrlParameter(e,t,r,n,s){const o=r.parameters.getProperty(e,void 0);o&&(!s||s.search(t)===-1)&&(n[t]=o.toLocaleLowerCase())}}var He;(function(i){i[i.Masked=0]="Masked",i[i.Removed=1]="Removed",i[i.Raw=2]="Raw"})(He||(He={}));var be=globalThis&&globalThis.__awaiter||function(i,e,t,r){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(r.next(c))}catch(p){o(p)}}function u(c){try{h(r.throw(c))}catch(p){o(p)}}function h(c){c.done?s(c.value):n(c.value).then(a,u)}h((r=r.apply(i,e||[])).next())})};class Ee{constructor(e,t){const r=e;C.throwIfNull(r,"speechConfig"),t!==null&&(t===void 0?this.audioConfig=typeof window=="undefined"?void 0:Q.fromDefaultSpeakerOutput():this.audioConfig=t),this.privProperties=r.properties.clone(),this.privDisposed=!1,this.privSynthesizing=!1,this.privConnectionFactory=new fi,this.synthesisRequestQueue=new ce,this.implCommonSynthesizeSetup()}get authorizationToken(){return this.properties.getProperty(d.SpeechServiceAuthorization_Token)}set authorizationToken(e){C.throwIfNullOrWhitespace(e,"token"),this.properties.setProperty(d.SpeechServiceAuthorization_Token,e)}get properties(){return this.privProperties}get autoDetectSourceLanguage(){return this.properties.getProperty(d.SpeechServiceConnection_AutoDetectSourceLanguages)===Pi}static FromConfig(e,t,r){const n=e;return t.properties.mergeTo(n.properties),new Ee(e,r)}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 r=this.properties.getProperty(d.SpeechServiceConnection_SynthLanguage,"en-US"),n=this.properties.getProperty(d.SpeechServiceConnection_SynthVoice,""),s=Ee.XMLEncode(e);return this.autoDetectSourceLanguage?r="en-US":n=n||t[r],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='${r}'>${s}</speak>`,s}speakTextAsync(e,t,r,n){this.speakImpl(e,!1,t,r,n)}speakSsmlAsync(e,t,r,n){this.speakImpl(e,!0,t,r,n)}getVoicesAsync(e=""){return be(this,void 0,void 0,function*(){return this.getVoices(e)})}close(e,t){C.throwIfDisposed(this.privDisposed),Kt(this.dispose(!0),e,t)}get internalData(){return this.privAdapter}dispose(e){return be(this,void 0,void 0,function*(){this.privDisposed||(e&&this.privAdapter&&(yield this.privAdapter.dispose()),this.privDisposed=!0)})}createSynthesizerConfig(e){return new yi(e,this.privProperties)}createSynthesisAdapter(e,t,r,n){return new ne(e,t,n,this,this.audioConfig)}implCommonSynthesizeSetup(){let e=typeof window!="undefined"?"Browser":"Node",t="unknown",r="unknown";typeof navigator!="undefined"&&(e=e+"/"+navigator.platform,t=navigator.userAgent,r=navigator.appVersion);const n=this.createSynthesizerConfig(new yt(new bt(new vi(e,t,r)))),s=this.privProperties.getProperty(d.SpeechServiceConnection_Key,void 0),o=s&&s!==""?new ii(s):new ue(()=>{const a=this.privProperties.getProperty(d.SpeechServiceAuthorization_Token,void 0);return Promise.resolve(a)},()=>{const a=this.privProperties.getProperty(d.SpeechServiceAuthorization_Token,void 0);return Promise.resolve(a)});this.privAdapter=this.createSynthesisAdapter(o,this.privConnectionFactory,this.audioConfig,n),this.privAdapter.audioOutputFormat=l.fromSpeechSynthesisOutputFormat(f[this.properties.getProperty(d.SpeechServiceConnection_SynthOutputFormat,void 0)]),this.privRestAdapter=new Ci(n)}speakImpl(e,t,r,n,s){try{C.throwIfDisposed(this.privDisposed);const o=E();let a;s instanceof vt?a=new Ue(s):s instanceof Ce?a=s:s!==void 0?a=new at(s):a=void 0,this.synthesisRequestQueue.enqueue(new oi(o,e,t,u=>{if(this.privSynthesizing=!1,r)try{r(u)}catch(h){n&&n(h)}r=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 be(this,void 0,void 0,function*(){const t=E(),r=yield this.privRestAdapter.getVoicesList(t);if(r.ok&&Array.isArray(r.json)){let n=r.json;return!!e&&e.length>0&&(n=n.filter(s=>!!s.Locale&&s.Locale.toLowerCase()===e.toLowerCase())),new St(t,n,void 0)}else return new St(t,void 0,`Error: ${r.status}: ${r.statusText}`)})}adapterSpeak(){return be(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 oi{constructor(e,t,r,n,s,o){this.requestId=e,this.text=t,this.isSSML=r,this.cb=n,this.err=s,this.dataStream=o}}class mt{constructor(e,t,r,n){this.privResultId=e,this.privReason=t,this.privErrorDetails=r,this.privProperties=n}get resultId(){return this.privResultId}get reason(){return this.privReason}get errorDetails(){return this.privErrorDetails}get properties(){return this.privProperties}}class Ae extends mt{constructor(e,t,r,n,s,o){super(e,t,n,s),this.privAudioData=r,this.privAudioDuration=o}get audioData(){return this.privAudioData}get audioDuration(){return this.privAudioDuration}}class Pe{constructor(e){this.privResult=e}get result(){return this.privResult}}class ai{constructor(e,t,r,n,s,o){this.privAudioOffset=e,this.privDuration=t,this.privText=r,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 ci{constructor(e,t){this.privAudioOffset=e,this.privText=t}get audioOffset(){return this.privAudioOffset}get text(){return this.privText}}class hi{constructor(e,t,r){this.privAudioOffset=e,this.privVisemeId=t,this.privAnimation=r}get audioOffset(){return this.privAudioOffset}get visemeId(){return this.privVisemeId}get animation(){return this.privAnimation}}class St extends mt{constructor(e,t,r){if(Array.isArray(t)){super(e,W.VoicesListRetrieved,void 0,new ee),this.privVoices=[];for(const n of t)this.privVoices.push(new ui(n))}else super(e,W.Canceled,r||"Error information unavailable",new ee)}get voices(){return this.privVoices}}var de;(function(i){i[i.Unknown=0]="Unknown",i[i.Female=1]="Female",i[i.Male=2]="Male"})(de||(de={}));var Re;(function(i){i[i.OnlineNeural=1]="OnlineNeural",i[i.OnlineStandard=2]="OnlineStandard",i[i.OfflineNeural=3]="OfflineNeural",i[i.OfflineStandard=4]="OfflineStandard"})(Re||(Re={}));class ui{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")?Re.OnlineStandard:Re.OnlineNeural,this.privGender=e.Gender==="Male"?de.Male:e.Gender==="Female"?de.Female:de.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 We=globalThis&&globalThis.__awaiter||function(i,e,t,r){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(r.next(c))}catch(p){o(p)}}function u(c){try{h(r.throw(c))}catch(p){o(p)}}function h(c){c.done?s(c.value):n(c.value).then(a,u)}h((r=r.apply(i,e||[])).next())})};const pi=60*30,wt={[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 Ve{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,r){this.privAudioBuffer!==void 0?(this.privAudioBuffer.push(e),this.updateSourceBuffer().then(()=>{t&&t()},n=>{r&&r(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()},r=>{t&&t(r)});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 r=new ArrayBuffer(this.privBytesReceived);this.privAudioOutputStream.read(r).then(()=>{r=ne.addHeader(r,this.privFormat);const n=new Blob([r],{type:wt[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=wt[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=pi,this.privSourceBuffer=this.privMediaSource.addSourceBuffer(t),this.privSourceBuffer.onupdate=()=>{this.updateSourceBuffer().catch(r=>{M.instance.onEvent(new he(r))})},this.privSourceBuffer.onupdateend=()=>{this.handleSourceBufferUpdateEnd().catch(r=>{M.instance.onEvent(new he(r))})},this.privSourceBuffer.onupdatestart=()=>{this.privAppendingToBuffer=!1}},this.updateSourceBuffer().catch(r=>{M.instance.onEvent(new he(r))})):(console.warn(`Format ${v[this.privFormat.formatTag]} could not be played by MSE, streaming playback is not enabled.`),this.privAudioOutputStream=new Ke,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()},r=>{t&&t(r)}),this.privIsPaused=!1)}get internalAudio(){return this.privAudio}updateSourceBuffer(){return We(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 We(this,void 0,void 0,function*(){this.canEndStream()&&this.sourceBufferAvailable()&&(this.privMediaSource.endOfStream(),yield this.notifyPlayback())})}notifyPlayback(){return We(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 j extends Be{constructor(e,t,r,n,s,o,a,u){if(!t)throw new k("path");if(!r)throw new k("requestId");const h={};if(h[y.Path]=t,h[y.RequestId]=r,h[y.RequestTimestamp]=new Date().toISOString(),n&&(h[y.ContentType]=n),o&&(h[y.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=r,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,r=null,n=null,s=null;const o={};if(e.headers)for(const a in e.headers)a&&(a.toLowerCase()===y.Path.toLowerCase()?t=e.headers[a]:a.toLowerCase()===y.RequestId.toLowerCase()?r=e.headers[a]:a.toLowerCase()===y.ContentType.toLowerCase()?n=e.headers[a]:a.toLowerCase()===y.RequestStreamId.toLowerCase()?s=e.headers[a]:o[a]=e.headers[a]);return new j(e.messageType,t,r,n,e.body,s,o,e.id)}}var gt;(function(i){i[i.Interactive=0]="Interactive",i[i.Conversation=1]="Conversation",i[i.Dictation=2]="Dictation"})(gt||(gt={}));var Ct;(function(i){i[i.Simple=0]="Simple",i[i.Detailed=1]="Detailed"})(Ct||(Ct={}));class yt{constructor(e){this.context=e}serialize(){return JSON.stringify(this,(e,t)=>{if(t&&typeof t=="object"){const r={};for(const n in t)Object.hasOwnProperty.call(t,n)&&(r[n&&n.charAt(0).toLowerCase()+n.substring(1)]=t[n]);return r}return t})}get Context(){return this.context}get Recognition(){return this.recognition}set Recognition(e){this.recognition=e.toLowerCase()}}class bt{constructor(e){this.system=new di,this.os=e}}class di{constructor(){const e="1.22.0";this.name="SpeechSDK",this.version=e,this.build="JavaScript",this.lang="JavaScript"}}class vi{constructor(e,t,r){this.platform=e,this.name=t,this.version=r}}var ie;(function(i){i.Bluetooth="Bluetooth",i.Wired="Wired",i.WiFi="WiFi",i.Cellular="Cellular",i.InBuilt="InBuilt",i.Unknown="Unknown"})(ie||(ie={}));var re;(function(i){i.Phone="Phone",i.Speaker="Speaker",i.Car="Car",i.Headset="Headset",i.Thermostat="Thermostat",i.Microphones="Microphones",i.Deskphone="Deskphone",i.RemoteControl="RemoteControl",i.Unknown="Unknown",i.File="File",i.Stream="Stream"})(re||(re={}));const Et=`\r
3
- `;class li{toConnectionMessage(e){const t=new T;try{if(e.messageType===w.Text){const r=e.textContent;let n={},s=null;if(r){const o=r.split(`\r
1
+ (function(z,T){typeof exports=="object"&&typeof module!="undefined"?module.exports=T():typeof define=="function"&&define.amd?define(T):(z=typeof globalThis!="undefined"?globalThis:z||self,z.CreativeOrangeAzureTextToSpeech=T())})(this,function(){"use strict";var Oi=Object.defineProperty;var _i=(z,T,q)=>T in z?Oi(z,T,{enumerable:!0,configurable:!0,writable:!0,value:q}):z[T]=q;var A=(z,T,q)=>(_i(z,typeof T!="symbol"?T+"":T,q),q);var z={},T,q=new Uint8Array(16);function Tt(){if(!T&&(T=typeof crypto!="undefined"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto!="undefined"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto),!T))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return T(q)}var Rt=/^(?:[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 kt(i){return typeof i=="string"&&Rt.test(i)}for(var P=[],De=0;De<256;++De)P.push((De+256).toString(16).substr(1));function Dt(i){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,t=(P[i[e+0]]+P[i[e+1]]+P[i[e+2]]+P[i[e+3]]+"-"+P[i[e+4]]+P[i[e+5]]+"-"+P[i[e+6]]+P[i[e+7]]+"-"+P[i[e+8]]+P[i[e+9]]+"-"+P[i[e+10]]+P[i[e+11]]+P[i[e+12]]+P[i[e+13]]+P[i[e+14]]+P[i[e+15]]).toLowerCase();if(!kt(t))throw TypeError("Stringified UUID is invalid");return t}function It(i,e,t){i=i||{};var r=i.random||(i.rng||Tt)();if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,e){t=t||0;for(var n=0;n<16;++n)e[t+n]=r[n];return e}return Dt(r)}const zt=()=>It(),E=()=>zt().replace(new RegExp("-","g"),"").toUpperCase();var S;(function(i){i[i.Debug=0]="Debug",i[i.Info=1]="Info",i[i.Warning=2]="Warning",i[i.Error=3]="Error",i[i.None=4]="None"})(S||(S={}));class F{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 F{constructor(e,t,r=S.Info){super(e,r),this.privAudioSourceId=t}get audioSourceId(){return this.privAudioSourceId}}class le extends se{constructor(e){super("AudioSourceInitializingEvent",e)}}class oe extends se{constructor(e){super("AudioSourceReadyEvent",e)}}class Ye extends se{constructor(e){super("AudioSourceOffEvent",e)}}class Ie extends se{constructor(e,t){super("AudioSourceErrorEvent",e,S.Error),this.privError=t}get error(){return this.privError}}class fe extends se{constructor(e,t,r){super(e,t),this.privAudioNodeId=r}get audioNodeId(){return this.privAudioNodeId}}class me extends fe{constructor(e,t){super("AudioStreamNodeAttachingEvent",e,t)}}class Se extends fe{constructor(e,t){super("AudioStreamNodeAttachedEvent",e,t)}}class K extends fe{constructor(e,t){super("AudioStreamNodeDetachedEvent",e,t)}}class et extends fe{constructor(e,t,r){super("AudioStreamNodeErrorEvent",e,t),this.privError=r}get error(){return this.privError}}class xt extends F{constructor(e,t,r=S.Info){super(e,r),this.privJsonResult=t}get jsonString(){return this.privJsonResult}}class J extends F{constructor(e,t,r=S.Info){super(e,r),this.privConnectionId=t}get connectionId(){return this.privConnectionId}}class Bt extends J{constructor(e,t,r){super("ConnectionStartEvent",e),this.privUri=t,this.privHeaders=r}get uri(){return this.privUri}get headers(){return this.privHeaders}}class Nt extends J{constructor(e){super("ConnectionEstablishedEvent",e)}}class Lt extends J{constructor(e,t,r){super("ConnectionClosedEvent",e,S.Debug),this.privReason=r,this.privStatusCode=t}get reason(){return this.privReason}get statusCode(){return this.privStatusCode}}class Ot extends J{constructor(e,t,r){super("ConnectionErrorEvent",e,S.Debug),this.privMessage=t,this.privType=r}get message(){return this.privMessage}get type(){return this.privType}}class tt extends J{constructor(e,t,r){super("ConnectionMessageReceivedEvent",e),this.privNetworkReceivedTime=t,this.privMessage=r}get networkReceivedTime(){return this.privNetworkReceivedTime}get message(){return this.privMessage}}class _t extends J{constructor(e,t,r){super("ConnectionMessageSentEvent",e),this.privNetworkSentTime=t,this.privMessage=r}get networkSentTime(){return this.privNetworkSentTime}get message(){return this.privMessage}}class D extends Error{constructor(e){super(e),this.name="ArgumentNull",this.message=e}}class B extends Error{constructor(e){super(e),this.name="InvalidOperation",this.message=e}}class ze extends Error{constructor(e,t){super(t),this.name=e+"ObjectDisposed",this.message=t}}var g;(function(i){i[i.Text=0]="Text",i[i.Binary=1]="Binary"})(g||(g={}));class xe{constructor(e,t,r,n){if(this.privBody=null,e===g.Text&&t&&typeof t!="string")throw new B("Payload must be a string");if(e===g.Binary&&t&&!(t instanceof ArrayBuffer))throw new B("Payload must be ArrayBuffer");switch(this.privMessageType=e,this.privBody=t,this.privHeaders=r||{},this.privId=n||E(),this.messageType){case g.Binary:this.privSize=this.binaryBody!==null?this.binaryBody.byteLength:0;break;case g.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===g.Binary)throw new B("Not supported for binary message");return this.privBody}get binaryBody(){if(this.privMessageType===g.Text)throw new B("Not supported for text message");return this.privBody}get id(){return this.privId}}class Be{constructor(e,t){this.privStatusCode=e,this.privReason=t}get statusCode(){return this.privStatusCode}get reason(){return this.privReason}}class H{constructor(e){this.privEventListeners={},this.privIsDisposed=!1,this.privConsoleListener=void 0,this.privMetadata=e}onEvent(e){if(this.isDisposed())throw new ze("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 R{static setEventSource(e){if(!e)throw new D("eventSource");R.privInstance=e}static get instance(){return R.privInstance}}R.privInstance=new H;var M;(function(i){i[i.None=0]="None",i[i.Connected=1]="Connected",i[i.Connecting=2]="Connecting",i[i.Disconnected=3]="Disconnected"})(M||(M={}));class L{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 r=this.privList.splice(e,t);return this.triggerSubscriptions(this.privRemoveSubscriptions),r}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 r=0;r<this.privList.length;r++)t.push(e(this.privList[r],r));return new L(t)}where(e){this.throwIfDisposed();const t=new L;for(let r=0;r<this.privList.length;r++)e(this.privList[r],r)&&t.add(this.privList[r]);return t}orderBy(e){this.throwIfDisposed();const r=this.toArray().sort(e);return new L(r)}orderByDesc(e){return this.throwIfDisposed(),this.orderBy((t,r)=>e(r,t))}clone(){return this.throwIfDisposed(),new L(this.toArray())}concat(e){return this.throwIfDisposed(),new L(this.privList.concat(e.toArray()))}concatArray(e){return this.throwIfDisposed(),new L(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 ze("List",this.privDisposeReason)}triggerSubscriptions(e){if(e)for(const t in e)t&&e[t]()}}var it;(function(i){i[i.None=0]="None",i[i.Resolved=1]="Resolved",i[i.Rejected=2]="Rejected"})(it||(it={}));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 Kt(i,e,t){i.then(r=>{try{e&&e(r)}catch(n){if(t)try{if(n instanceof Error){const s=n;t(s.name+": "+s.message)}else t(n)}catch{}}},r=>{if(t)try{if(r instanceof Error){const n=r;t(n.name+": "+n.message)}else t(r)}catch{}})}var rt=globalThis&&globalThis.__awaiter||function(i,e,t,r){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(h){try{c(r.next(h))}catch(p){o(p)}}function u(h){try{c(r.throw(h))}catch(p){o(p)}}function c(h){h.done?s(h.value):n(h.value).then(a,u)}c((r=r.apply(i,e||[])).next())})},ae;(function(i){i[i.Dequeue=0]="Dequeue",i[i.Peek=1]="Peek"})(ae||(ae={}));class he{constructor(e){this.privPromiseStore=new L,this.privIsDrainInProgress=!1,this.privIsDisposing=!1,this.privDisposeReason=null,this.privList=e||new L,this.privDetachables=[],this.privSubscribers=new L,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:ae.Dequeue}),this.drain()),e.promise}peek(){this.throwIfDispose();const e=new k;return this.privSubscribers&&(this.privSubscribers.add({deferral:e,type:ae.Peek}),this.drain()),e.promise}length(){return this.throwIfDispose(),this.privList.length()}isDisposed(){return this.privSubscribers==null}drainAndDispose(e,t){return rt(this,void 0,void 0,function*(){if(!this.isDisposed()&&!this.privIsDisposing){this.privDisposeReason=t,this.privIsDisposing=!0;const r=this.privSubscribers;if(r){for(;r.length()>0;)r.removeFirst().deferral.resolve(void 0);this.privSubscribers===r&&(this.privSubscribers=r)}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 rt(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 r=e.removeFirst();if(r.type===ae.Peek)r.deferral.resolve(t.first());else{const n=t.removeFirst();r.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 B(this.privDisposeReason):new ze("Queue");if(this.privIsDisposing)throw new B("Queue disposing")}}class ge{constructor(e,t,r){if(this.privPayload=null,!t)throw new D("payload");if(e===g.Binary&&t.__proto__.constructor.name!=="ArrayBuffer")throw new B("Payload must be ArrayBuffer");if(e===g.Text&&typeof t!="string")throw new B("Payload must be a string");this.privMessageType=e,this.privPayload=t,this.privId=r||E()}get messageType(){return this.privMessageType}get payload(){return this.privPayload}get textContent(){if(this.privMessageType===g.Binary)throw new B("Not supported for binary message");return this.privPayload}get binaryContent(){if(this.privMessageType===g.Text)throw new B("Not supported for text message");return this.privPayload}get id(){return this.privId}}class Ht{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 r=t.length*2,n=new ArrayBuffer(r),s=new DataView(n);return this.floatTo16BitPCM(s,0,t),n}setString(e,t,r){for(let n=0;n<r.length;n++)e.setUint8(t+n,r.charCodeAt(n))}floatTo16BitPCM(e,t,r){for(let n=0;n<r.length;n++,t+=2){const s=Math.max(-1,Math.min(1,r[n]));e.setInt16(t,s<0?s*32768:s*32767,!0)}}downSampleAudioFrame(e,t,r){if(!e)return null;if(r===t||r>t)return e;const n=t/r,s=Math.round(e.length/n),o=new Float32Array(s);let a=0,u=0;for(;u<s;){const c=Math.round((u+1)*n);let h=0,p=0;for(;a<c&&a<e.length;)h+=e[a++],p++;o[u++]=h/p}return o}}var Ut=globalThis&&globalThis.__awaiter||function(i,e,t,r){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(h){try{c(r.next(h))}catch(p){o(p)}}function u(h){try{c(r.throw(h))}catch(p){o(p)}}function c(h){h.done?s(h.value):n(h.value).then(a,u)}c((r=r.apply(i,e||[])).next())})};class nt{constructor(e){this.privIsWriteEnded=!1,this.privIsReadEnded=!1,this.privId=e||E(),this.privReaderQueue=new he}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 B("Stream read has already finished");return this.privReaderQueue.dequeue().then(e=>Ut(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 he)}throwIfClosed(){if(this.privIsWriteEnded)throw new B("Stream closed")}}class Ne extends nt{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 r=Math.min(e.buffer.byteLength-t,this.privTargetChunkSize-this.privNextBufferReadyBytes),n=new Uint8Array(this.privNextBufferToWrite),s=new Uint8Array(e.buffer.slice(t,r+t));n.set(s,this.privNextBufferReadyBytes),this.privNextBufferReadyBytes+=r,t+=r,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 I extends F{constructor(e,t,r){super(e,t),this.privSignature=r}}class Wt extends I{constructor(e){super("OCSPMemoryCacheHitEvent",S.Debug,e)}}class Vt extends I{constructor(e){super("OCSPCacheMissEvent",S.Debug,e)}}class qt extends I{constructor(e){super("OCSPDiskCacheHitEvent",S.Debug,e)}}class jt extends I{constructor(e){super("OCSPCacheUpdateNeededEvent",S.Debug,e)}}class $t extends I{constructor(e){super("OCSPMemoryCacheStoreEvent",S.Debug,e)}}class Gt extends I{constructor(e){super("OCSPDiskCacheStoreEvent",S.Debug,e)}}class Ft extends I{constructor(e){super("OCSPCacheUpdateCompleteEvent",S.Debug,e)}}class Jt extends I{constructor(){super("OCSPStapleReceivedEvent",S.Debug,"")}}class Qt extends I{constructor(e,t){super("OCSPCacheEntryExpiredEvent",S.Debug,e),this.privExpireTime=t}}class Xt extends I{constructor(e,t,r){super("OCSPCacheEntryNeedsRefreshEvent",S.Debug,e),this.privExpireTime=r,this.privStartTime=t}}class Zt extends I{constructor(e,t,r){super("OCSPCacheHitEvent",S.Debug,e),this.privExpireTime=r,this.privExpireTimeString=new Date(r).toLocaleDateString(),this.privStartTime=t,this.privStartTimeString=new Date(t).toLocaleTimeString()}}class Yt extends I{constructor(e,t){super("OCSPVerificationFailedEvent",S.Debug,e),this.privError=t}}class st extends I{constructor(e,t){super("OCSPCacheFetchErrorEvent",S.Debug,e),this.privError=t}}class ei extends I{constructor(e){super("OCSPResponseRetrievedEvent",S.Debug,e)}}class ti extends I{constructor(e,t){super("OCSPCacheUpdateErrorEvent",S.Debug,e),this.privError=t}}class ce extends F{constructor(e){super("BackgroundEvent",S.Error),this.privError=e}get error(){return this.privError}}class C{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(C.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(C.throwIfNullOrUndefined(e,t),e.length===0)throw new Error("throwIfArrayEmptyOrWhitespace:"+t);for(const r of e)C.throwIfNullOrWhitespace(r,t)}static throwIfFileDoesNotExist(e,t){C.throwIfNullOrWhitespace(e,t)}static throwIfNotUndefined(e,t){if(e!==void 0)throw new Error("throwIfNotUndefined:"+t)}}class y{}y.AuthKey="Ocp-Apim-Subscription-Key",y.ConnectionId="X-ConnectionId",y.ContentType="Content-Type",y.CustomCommandsAppId="X-CommandsAppId",y.Path="Path",y.RequestId="X-RequestId",y.RequestStreamId="X-StreamId",y.RequestTimestamp="X-Timestamp";class Le{constructor(e,t){this.privHeaderName=e,this.privToken=t}get headerName(){return this.privHeaderName}get token(){return this.privToken}}class ii{constructor(e){if(!e)throw new D("subscriptionKey");this.privAuthInfo=new Le(y.AuthKey,e)}fetch(e){return Promise.resolve(this.privAuthInfo)}fetchOnExpiry(e){return Promise.resolve(this.privAuthInfo)}}const ot="Authorization";class ue{constructor(e,t){if(!e)throw new D("fetchCallback");if(!t)throw new D("fetchOnExpiryCallback");this.privFetchCallback=e,this.privFetchOnExpiryCallback=t}fetch(e){return this.privFetchCallback(e).then(t=>new Le(ot,ue.privTokenPrefix+t))}fetchOnExpiry(e){return this.privFetchOnExpiryCallback(e).then(t=>new Le(ot,ue.privTokenPrefix+t))}}ue.privTokenPrefix="bearer ";class at{constructor(e){C.throwIfNullOrUndefined(void 0,`
2
+ File System access not available, please use Push or PullAudioOutputStream`),this.privFd=(void 0)(e,"w")}set format(e){C.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){C.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(i){i[i.PCM=1]="PCM",i[i.MuLaw=2]="MuLaw",i[i.Siren=3]="Siren",i[i.MP3=4]="MP3",i[i.SILKSkype=5]="SILKSkype",i[i.OGG_OPUS=6]="OGG_OPUS",i[i.WEBM_OPUS=7]="WEBM_OPUS",i[i.ALaw=8]="ALaw",i[i.FLAC=9]="FLAC",i[i.OPUS=10]="OPUS"})(v||(v={}));class we{static getDefaultInputFormat(){return U.getDefaultInputFormat()}static getWaveFormat(e,t,r,n){return new U(e,t,r,n)}static getWaveFormatPCM(e,t,r){return new U(e,t,r)}}class U extends we{constructor(e=16e3,t=16,r=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=r,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 U}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,r){for(let n=0;n<r.length;n++)e.setUint8(t+n,r.charCodeAt(n))}}var Oe=globalThis&&globalThis.__awaiter||function(i,e,t,r){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(h){try{c(r.next(h))}catch(p){o(p)}}function u(h){try{c(r.throw(h))}catch(p){o(p)}}function c(h){h.done?s(h.value):n(h.value).then(a,u)}c((r=r.apply(i,e||[])).next())})};class _e{constructor(){}static createPushStream(e){return ht.create(e)}static createPullStream(e,t){return ct.create(e,t)}}class ht extends _e{static create(e){return new ri(e)}}class ri extends ht{constructor(e){super(),e===void 0?this.privFormat=U.getDefaultInputFormat():this.privFormat=e,this.privEvents=new H,this.privId=E(),this.privStream=new Ne(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 r=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(r)):(typeof Blob!="undefined"?t.push(s.buffer):r=Buffer.concat([r,this.toBuffer(s.buffer)]),n()));return n()})}turnOn(){this.onEvent(new le(this.privId)),this.onEvent(new oe(this.privId))}attach(e){return Oe(this,void 0,void 0,function*(){this.onEvent(new me(this.privId,e)),yield this.turnOn();const t=this.privStream;return this.onEvent(new Se(this.privId,e)),{detach:()=>Oe(this,void 0,void 0,function*(){return this.onEvent(new K(this.privId,e)),this.turnOff()}),id:()=>e,read:()=>t.read()}})}detach(e){this.onEvent(new K(this.privId,e))}turnOff(){}get events(){return this.privEvents}get deviceInfo(){return Promise.resolve({bitspersample:this.privFormat.bitsPerSample,channelcount:this.privFormat.channels,connectivity:ie.Unknown,manufacturer:"Speech SDK",model:"PushStream",samplerate:this.privFormat.samplesPerSec,type:re.Stream})}onEvent(e){this.privEvents.onEvent(e),R.instance.onEvent(e)}toBuffer(e){const t=Buffer.alloc(e.byteLength),r=new Uint8Array(e);for(let n=0;n<t.length;++n)t[n]=r[n];return t}}class ct extends _e{constructor(){super()}static create(e,t){return new ut(e,t)}}class ut extends ct{constructor(e,t){super(),t===void 0?this.privFormat=we.getDefaultInputFormat():this.privFormat=t,this.privEvents=new H,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 le(this.privId)),this.onEvent(new oe(this.privId))}attach(e){return Oe(this,void 0,void 0,function*(){return this.onEvent(new me(this.privId,e)),yield this.turnOn(),this.onEvent(new Se(this.privId,e)),{detach:()=>(this.privCallback.close(),this.onEvent(new K(this.privId,e)),this.turnOff()),id:()=>e,read:()=>{let t=0,r;for(;t<this.privBufferSize;){const n=new ArrayBuffer(this.privBufferSize-t),s=this.privCallback.read(n);if(r===void 0?r=n:new Int8Array(r).set(new Int8Array(n),t),s===0)break;t+=s}return Promise.resolve({buffer:r.slice(0,t),isEnd:this.privIsClosed||t===0,timeReceived:Date.now()})}}})}detach(e){this.onEvent(new K(this.privId,e))}turnOff(){}get events(){return this.privEvents}get deviceInfo(){return Promise.resolve({bitspersample:this.privFormat.bitsPerSample,channelcount:this.privFormat.channels,connectivity:ie.Unknown,manufacturer:"Speech SDK",model:"PullStream",samplerate:this.privFormat.samplesPerSec,type:re.Stream})}onEvent(e){this.privEvents.onEvent(e),R.instance.onEvent(e)}}var f;(function(i){i[i.Raw8Khz8BitMonoMULaw=0]="Raw8Khz8BitMonoMULaw",i[i.Riff16Khz16KbpsMonoSiren=1]="Riff16Khz16KbpsMonoSiren",i[i.Audio16Khz16KbpsMonoSiren=2]="Audio16Khz16KbpsMonoSiren",i[i.Audio16Khz32KBitRateMonoMp3=3]="Audio16Khz32KBitRateMonoMp3",i[i.Audio16Khz128KBitRateMonoMp3=4]="Audio16Khz128KBitRateMonoMp3",i[i.Audio16Khz64KBitRateMonoMp3=5]="Audio16Khz64KBitRateMonoMp3",i[i.Audio24Khz48KBitRateMonoMp3=6]="Audio24Khz48KBitRateMonoMp3",i[i.Audio24Khz96KBitRateMonoMp3=7]="Audio24Khz96KBitRateMonoMp3",i[i.Audio24Khz160KBitRateMonoMp3=8]="Audio24Khz160KBitRateMonoMp3",i[i.Raw16Khz16BitMonoTrueSilk=9]="Raw16Khz16BitMonoTrueSilk",i[i.Riff16Khz16BitMonoPcm=10]="Riff16Khz16BitMonoPcm",i[i.Riff8Khz16BitMonoPcm=11]="Riff8Khz16BitMonoPcm",i[i.Riff24Khz16BitMonoPcm=12]="Riff24Khz16BitMonoPcm",i[i.Riff8Khz8BitMonoMULaw=13]="Riff8Khz8BitMonoMULaw",i[i.Raw16Khz16BitMonoPcm=14]="Raw16Khz16BitMonoPcm",i[i.Raw24Khz16BitMonoPcm=15]="Raw24Khz16BitMonoPcm",i[i.Raw8Khz16BitMonoPcm=16]="Raw8Khz16BitMonoPcm",i[i.Ogg16Khz16BitMonoOpus=17]="Ogg16Khz16BitMonoOpus",i[i.Ogg24Khz16BitMonoOpus=18]="Ogg24Khz16BitMonoOpus",i[i.Raw48Khz16BitMonoPcm=19]="Raw48Khz16BitMonoPcm",i[i.Riff48Khz16BitMonoPcm=20]="Riff48Khz16BitMonoPcm",i[i.Audio48Khz96KBitRateMonoMp3=21]="Audio48Khz96KBitRateMonoMp3",i[i.Audio48Khz192KBitRateMonoMp3=22]="Audio48Khz192KBitRateMonoMp3",i[i.Ogg48Khz16BitMonoOpus=23]="Ogg48Khz16BitMonoOpus",i[i.Webm16Khz16BitMonoOpus=24]="Webm16Khz16BitMonoOpus",i[i.Webm24Khz16BitMonoOpus=25]="Webm24Khz16BitMonoOpus",i[i.Raw24Khz16BitMonoTrueSilk=26]="Raw24Khz16BitMonoTrueSilk",i[i.Raw8Khz8BitMonoALaw=27]="Raw8Khz8BitMonoALaw",i[i.Riff8Khz8BitMonoALaw=28]="Riff8Khz8BitMonoALaw",i[i.Webm24Khz16Bit24KbpsMonoOpus=29]="Webm24Khz16Bit24KbpsMonoOpus",i[i.Audio16Khz16Bit32KbpsMonoOpus=30]="Audio16Khz16Bit32KbpsMonoOpus",i[i.Audio24Khz16Bit48KbpsMonoOpus=31]="Audio24Khz16Bit48KbpsMonoOpus",i[i.Audio24Khz16Bit24KbpsMonoOpus=32]="Audio24Khz16Bit24KbpsMonoOpus",i[i.Raw22050Hz16BitMonoPcm=33]="Raw22050Hz16BitMonoPcm",i[i.Riff22050Hz16BitMonoPcm=34]="Riff22050Hz16BitMonoPcm",i[i.Raw44100Hz16BitMonoPcm=35]="Raw44100Hz16BitMonoPcm",i[i.Riff44100Hz16BitMonoPcm=36]="Riff44100Hz16BitMonoPcm"})(f||(f={}));class l extends U{constructor(e,t,r,n,s,o,a,u,c){super(r,o,t,e),this.formatTag=e,this.avgBytesPerSec=n,this.blockAlign=s,this.priAudioFormatString=a,this.priRequestAudioFormatString=u,this.priHasHeader=c}static fromSpeechSynthesisOutputFormat(e){return e===void 0?l.getDefaultOutputFormat():l.fromSpeechSynthesisOutputFormatString(l.SpeechSynthesisOutputFormatToString[e])}static fromSpeechSynthesisOutputFormatString(e){switch(e){case"raw-8khz-8bit-mono-mulaw":return new l(v.MuLaw,1,8e3,8e3,1,8,e,e,!1);case"riff-16khz-16kbps-mono-siren":return new l(v.Siren,1,16e3,2e3,40,0,e,"audio-16khz-16kbps-mono-siren",!0);case"audio-16khz-16kbps-mono-siren":return new l(v.Siren,1,16e3,2e3,40,0,e,e,!1);case"audio-16khz-32kbitrate-mono-mp3":return new l(v.MP3,1,16e3,32<<7,2,16,e,e,!1);case"audio-16khz-128kbitrate-mono-mp3":return new l(v.MP3,1,16e3,128<<7,2,16,e,e,!1);case"audio-16khz-64kbitrate-mono-mp3":return new l(v.MP3,1,16e3,64<<7,2,16,e,e,!1);case"audio-24khz-48kbitrate-mono-mp3":return new l(v.MP3,1,24e3,48<<7,2,16,e,e,!1);case"audio-24khz-96kbitrate-mono-mp3":return new l(v.MP3,1,24e3,96<<7,2,16,e,e,!1);case"audio-24khz-160kbitrate-mono-mp3":return new l(v.MP3,1,24e3,160<<7,2,16,e,e,!1);case"raw-16khz-16bit-mono-truesilk":return new l(v.SILKSkype,1,16e3,32e3,2,16,e,e,!1);case"riff-8khz-16bit-mono-pcm":return new l(v.PCM,1,8e3,16e3,2,16,e,"raw-8khz-16bit-mono-pcm",!0);case"riff-24khz-16bit-mono-pcm":return new l(v.PCM,1,24e3,48e3,2,16,e,"raw-24khz-16bit-mono-pcm",!0);case"riff-8khz-8bit-mono-mulaw":return new l(v.MuLaw,1,8e3,8e3,1,8,e,"raw-8khz-8bit-mono-mulaw",!0);case"raw-16khz-16bit-mono-pcm":return new l(v.PCM,1,16e3,32e3,2,16,e,"raw-16khz-16bit-mono-pcm",!1);case"raw-24khz-16bit-mono-pcm":return new l(v.PCM,1,24e3,48e3,2,16,e,"raw-24khz-16bit-mono-pcm",!1);case"raw-8khz-16bit-mono-pcm":return new l(v.PCM,1,8e3,16e3,2,16,e,"raw-8khz-16bit-mono-pcm",!1);case"ogg-16khz-16bit-mono-opus":return new l(v.OGG_OPUS,1,16e3,8192,2,16,e,e,!1);case"ogg-24khz-16bit-mono-opus":return new l(v.OGG_OPUS,1,24e3,8192,2,16,e,e,!1);case"raw-48khz-16bit-mono-pcm":return new l(v.PCM,1,48e3,96e3,2,16,e,"raw-48khz-16bit-mono-pcm",!1);case"riff-48khz-16bit-mono-pcm":return new l(v.PCM,1,48e3,96e3,2,16,e,"raw-48khz-16bit-mono-pcm",!0);case"audio-48khz-96kbitrate-mono-mp3":return new l(v.MP3,1,48e3,96<<7,2,16,e,e,!1);case"audio-48khz-192kbitrate-mono-mp3":return new l(v.MP3,1,48e3,192<<7,2,16,e,e,!1);case"ogg-48khz-16bit-mono-opus":return new l(v.OGG_OPUS,1,48e3,12e3,2,16,e,e,!1);case"webm-16khz-16bit-mono-opus":return new l(v.WEBM_OPUS,1,16e3,4e3,2,16,e,e,!1);case"webm-24khz-16bit-mono-opus":return new l(v.WEBM_OPUS,1,24e3,6e3,2,16,e,e,!1);case"webm-24khz-16bit-24kbps-mono-opus":return new l(v.WEBM_OPUS,1,24e3,3e3,2,16,e,e,!1);case"audio-16khz-16bit-32kbps-mono-opus":return new l(v.OPUS,1,16e3,4e3,2,16,e,e,!1);case"audio-24khz-16bit-48kbps-mono-opus":return new l(v.OPUS,1,24e3,6e3,2,16,e,e,!1);case"audio-24khz-16bit-24kbps-mono-opus":return new l(v.OPUS,1,24e3,3e3,2,16,e,e,!1);case"audio-24khz-16bit-mono-flac":return new l(v.FLAC,1,24e3,24e3,2,16,e,e,!1);case"audio-48khz-16bit-mono-flac":return new l(v.FLAC,1,48e3,3e4,2,16,e,e,!1);case"raw-24khz-16bit-mono-truesilk":return new l(v.SILKSkype,1,24e3,48e3,2,16,e,e,!1);case"raw-8khz-8bit-mono-alaw":return new l(v.ALaw,1,8e3,8e3,1,8,e,e,!1);case"riff-8khz-8bit-mono-alaw":return new l(v.ALaw,1,8e3,8e3,1,8,e,"raw-8khz-8bit-mono-alaw",!0);case"raw-22050hz-16bit-mono-pcm":return new l(v.PCM,1,22050,44100,2,16,e,e,!1);case"riff-22050hz-16bit-mono-pcm":return new l(v.PCM,1,22050,44100,2,16,e,"raw-22050hz-16bit-mono-pcm",!0);case"raw-44100hz-16bit-mono-pcm":return new l(v.PCM,1,44100,88200,2,16,e,e,!1);case"riff-44100hz-16bit-mono-pcm":return new l(v.PCM,1,44100,88200,2,16,e,"raw-44100hz-16bit-mono-pcm",!0);case"riff-16khz-16bit-mono-pcm":default:return new l(v.PCM,1,16e3,32e3,2,16,"riff-16khz-16bit-mono-pcm","raw-16khz-16bit-mono-pcm",!0)}}static getDefaultOutputFormat(){return l.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}}l.SpeechSynthesisOutputFormatToString={[f.Raw8Khz8BitMonoMULaw]:"raw-8khz-8bit-mono-mulaw",[f.Riff16Khz16KbpsMonoSiren]:"riff-16khz-16kbps-mono-siren",[f.Audio16Khz16KbpsMonoSiren]:"audio-16khz-16kbps-mono-siren",[f.Audio16Khz32KBitRateMonoMp3]:"audio-16khz-32kbitrate-mono-mp3",[f.Audio16Khz128KBitRateMonoMp3]:"audio-16khz-128kbitrate-mono-mp3",[f.Audio16Khz64KBitRateMonoMp3]:"audio-16khz-64kbitrate-mono-mp3",[f.Audio24Khz48KBitRateMonoMp3]:"audio-24khz-48kbitrate-mono-mp3",[f.Audio24Khz96KBitRateMonoMp3]:"audio-24khz-96kbitrate-mono-mp3",[f.Audio24Khz160KBitRateMonoMp3]:"audio-24khz-160kbitrate-mono-mp3",[f.Raw16Khz16BitMonoTrueSilk]:"raw-16khz-16bit-mono-truesilk",[f.Riff16Khz16BitMonoPcm]:"riff-16khz-16bit-mono-pcm",[f.Riff8Khz16BitMonoPcm]:"riff-8khz-16bit-mono-pcm",[f.Riff24Khz16BitMonoPcm]:"riff-24khz-16bit-mono-pcm",[f.Riff8Khz8BitMonoMULaw]:"riff-8khz-8bit-mono-mulaw",[f.Raw16Khz16BitMonoPcm]:"raw-16khz-16bit-mono-pcm",[f.Raw24Khz16BitMonoPcm]:"raw-24khz-16bit-mono-pcm",[f.Raw8Khz16BitMonoPcm]:"raw-8khz-16bit-mono-pcm",[f.Ogg16Khz16BitMonoOpus]:"ogg-16khz-16bit-mono-opus",[f.Ogg24Khz16BitMonoOpus]:"ogg-24khz-16bit-mono-opus",[f.Raw48Khz16BitMonoPcm]:"raw-48khz-16bit-mono-pcm",[f.Riff48Khz16BitMonoPcm]:"riff-48khz-16bit-mono-pcm",[f.Audio48Khz96KBitRateMonoMp3]:"audio-48khz-96kbitrate-mono-mp3",[f.Audio48Khz192KBitRateMonoMp3]:"audio-48khz-192kbitrate-mono-mp3",[f.Ogg48Khz16BitMonoOpus]:"ogg-48khz-16bit-mono-opus",[f.Webm16Khz16BitMonoOpus]:"webm-16khz-16bit-mono-opus",[f.Webm24Khz16BitMonoOpus]:"webm-24khz-16bit-mono-opus",[f.Webm24Khz16Bit24KbpsMonoOpus]:"webm-24khz-16bit-24kbps-mono-opus",[f.Raw24Khz16BitMonoTrueSilk]:"raw-24khz-16bit-mono-truesilk",[f.Raw8Khz8BitMonoALaw]:"raw-8khz-8bit-mono-alaw",[f.Riff8Khz8BitMonoALaw]:"riff-8khz-8bit-mono-alaw",[f.Audio16Khz16Bit32KbpsMonoOpus]:"audio-16khz-16bit-32kbps-mono-opus",[f.Audio24Khz16Bit48KbpsMonoOpus]:"audio-24khz-16bit-48kbps-mono-opus",[f.Audio24Khz16Bit24KbpsMonoOpus]:"audio-24khz-16bit-24kbps-mono-opus",[f.Raw22050Hz16BitMonoPcm]:"raw-22050hz-16bit-mono-pcm",[f.Riff22050Hz16BitMonoPcm]:"riff-22050hz-16bit-mono-pcm",[f.Raw44100Hz16BitMonoPcm]:"raw-44100hz-16bit-mono-pcm",[f.Riff44100Hz16BitMonoPcm]:"riff-44100hz-16bit-mono-pcm"};var ni=globalThis&&globalThis.__awaiter||function(i,e,t,r){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(h){try{c(r.next(h))}catch(p){o(p)}}function u(h){try{c(r.throw(h))}catch(p){o(p)}}function c(h){h.done?s(h.value):n(h.value).then(a,u)}c((r=r.apply(i,e||[])).next())})};class pt{constructor(){}static createPullStream(){return Ce.create()}}class Ce extends pt{static create(){return new Ke}}class Ke extends Ce{constructor(){super(),this.privId=E(),this.privStream=new nt}set format(e){e==null&&(this.privFormat=l.getDefaultOutputFormat()),this.privFormat=e}get format(){return this.privFormat}get isClosed(){return this.privStream.isClosed}id(){return this.privId}read(e){return ni(this,void 0,void 0,function*(){const t=new Int8Array(e);let r=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),r=this.privLastChunkView.length,this.privLastChunkView=void 0}for(;r<e.byteLength&&!this.privStream.isReadEnded;){const n=yield this.privStream.read();if(n!==void 0&&!n.isEnd){let s;n.buffer.byteLength>e.byteLength-r?(s=n.buffer.slice(0,e.byteLength-r),this.privLastChunkView=new Int8Array(n.buffer.slice(e.byteLength-r))):s=n.buffer,t.set(new Int8Array(s),r),r+=s.byteLength}else this.privStream.readEnded()}return r})}write(e){C.throwIfNullOrUndefined(this.privStream,"must set format before writing"),this.privStream.writeStreamChunk({buffer:e,isEnd:!1,timeReceived:Date.now()})}close(){this.privStream.close()}}class dt extends pt{constructor(){super()}static create(e){return new He(e)}}class He extends dt{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 Q{static fromDefaultMicrophoneInput(){const e=new Qe(!0);return new X(new N(e))}static fromMicrophoneInput(e){const t=new Qe(!0);return new X(new N(t,e))}static fromWavFileInput(e,t="unnamedBuffer.wav"){return new X(new Ti(e,t))}static fromStreamInput(e){if(e instanceof si)return new X(new ut(e));if(e instanceof _e)return new X(e);if(typeof MediaStream!="undefined"&&e instanceof MediaStream){const t=new Qe(!1);return new X(new N(t,null,null,e))}throw new Error("Not Supported Type")}static fromDefaultSpeakerOutput(){return new Z(new Ve)}static fromSpeakerOutput(e){if(e===void 0)return Q.fromDefaultSpeakerOutput();if(e instanceof Ve)return new Z(e);throw new Error("Not Supported Type")}static fromAudioFileOutput(e){return new Z(new at(e))}static fromStreamOutput(e){if(e instanceof vt)return new Z(new He(e));if(e instanceof dt)return new Z(e);if(e instanceof Ce)return new Z(e);throw new Error("Not Supported Type")}}class X extends Q{constructor(e){super(),this.privSource=e}get format(){return this.privSource.format}close(e,t){this.privSource.turnOff().then(()=>{e&&e()},r=>{t&&t(r)})}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(C.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 Z extends Q{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 ye;(function(i){i[i.Error=0]="Error",i[i.EndOfStream=1]="EndOfStream"})(ye||(ye={}));class si{}class vt{}var pe;(function(i){i[i.Simple=0]="Simple",i[i.Detailed=1]="Detailed"})(pe||(pe={}));var W;(function(i){i[i.NoMatch=0]="NoMatch",i[i.Canceled=1]="Canceled",i[i.RecognizingSpeech=2]="RecognizingSpeech",i[i.RecognizedSpeech=3]="RecognizedSpeech",i[i.RecognizedKeyword=4]="RecognizedKeyword",i[i.RecognizingIntent=5]="RecognizingIntent",i[i.RecognizedIntent=6]="RecognizedIntent",i[i.TranslatingSpeech=7]="TranslatingSpeech",i[i.TranslatedSpeech=8]="TranslatedSpeech",i[i.SynthesizingAudio=9]="SynthesizingAudio",i[i.SynthesizingAudioCompleted=10]="SynthesizingAudioCompleted",i[i.SynthesizingAudioStarted=11]="SynthesizingAudioStarted",i[i.EnrollingVoiceProfile=12]="EnrollingVoiceProfile",i[i.EnrolledVoiceProfile=13]="EnrolledVoiceProfile",i[i.RecognizedSpeakers=14]="RecognizedSpeakers",i[i.RecognizedSpeaker=15]="RecognizedSpeaker",i[i.ResetVoiceProfile=16]="ResetVoiceProfile",i[i.DeletedVoiceProfile=17]="DeletedVoiceProfile",i[i.VoicesListRetrieved=18]="VoicesListRetrieved"})(W||(W={}));class lt{constructor(){}static fromSubscription(e,t){C.throwIfNullOrWhitespace(e,"subscriptionKey"),C.throwIfNullOrWhitespace(t,"region");const r=new Y;return r.setProperty(d.SpeechServiceConnection_Region,t),r.setProperty(d.SpeechServiceConnection_IntentRegion,t),r.setProperty(d.SpeechServiceConnection_Key,e),r}static fromEndpoint(e,t){C.throwIfNull(e,"endpoint");const r=new Y;return r.setProperty(d.SpeechServiceConnection_Endpoint,e.href),t!==void 0&&r.setProperty(d.SpeechServiceConnection_Key,t),r}static fromHost(e,t){C.throwIfNull(e,"hostName");const r=new Y;return r.setProperty(d.SpeechServiceConnection_Host,e.protocol+"//"+e.hostname+(e.port===""?"":":"+e.port)),t!==void 0&&r.setProperty(d.SpeechServiceConnection_Key,t),r}static fromAuthorizationToken(e,t){C.throwIfNull(e,"authorizationToken"),C.throwIfNullOrWhitespace(t,"region");const r=new Y;return r.setProperty(d.SpeechServiceConnection_Region,t),r.setProperty(d.SpeechServiceConnection_IntentRegion,t),r.authorizationToken=e,r}close(){}}class Y extends lt{constructor(){super(),this.privProperties=new ee,this.speechRecognitionLanguage="en-US",this.outputFormat=pe.Simple}get properties(){return this.privProperties}get endPoint(){return new URL(this.privProperties.getProperty(d.SpeechServiceConnection_Endpoint))}get subscriptionKey(){return this.privProperties.getProperty(d.SpeechServiceConnection_Key)}get region(){return this.privProperties.getProperty(d.SpeechServiceConnection_Region)}get authorizationToken(){return this.privProperties.getProperty(d.SpeechServiceAuthorization_Token)}set authorizationToken(e){this.privProperties.setProperty(d.SpeechServiceAuthorization_Token,e)}get speechRecognitionLanguage(){return this.privProperties.getProperty(d.SpeechServiceConnection_RecoLanguage)}set speechRecognitionLanguage(e){this.privProperties.setProperty(d.SpeechServiceConnection_RecoLanguage,e)}get autoDetectSourceLanguages(){return this.privProperties.getProperty(d.SpeechServiceConnection_AutoDetectSourceLanguages)}set autoDetectSourceLanguages(e){this.privProperties.setProperty(d.SpeechServiceConnection_AutoDetectSourceLanguages,e)}get outputFormat(){return pe[this.privProperties.getProperty(At,void 0)]}set outputFormat(e){this.privProperties.setProperty(At,pe[e])}get endpointId(){return this.privProperties.getProperty(d.SpeechServiceConnection_EndpointId)}set endpointId(e){this.privProperties.setProperty(d.SpeechServiceConnection_EndpointId,e)}setProperty(e,t){C.throwIfNull(t,"value"),this.privProperties.setProperty(e,t)}getProperty(e,t){return this.privProperties.getProperty(e,t)}setProxy(e,t,r,n){this.setProperty(d[d.SpeechServiceConnection_ProxyHostName],e),this.setProperty(d[d.SpeechServiceConnection_ProxyPort],t),this.setProperty(d[d.SpeechServiceConnection_ProxyUserName],r),this.setProperty(d[d.SpeechServiceConnection_ProxyPassword],n)}setServiceProperty(e,t){const r=JSON.parse(this.privProperties.getProperty(Fe,"{}"));r[e]=t,this.privProperties.setProperty(Fe,JSON.stringify(r))}setProfanity(e){this.privProperties.setProperty(d.SpeechServiceResponse_ProfanityOption,Ue[e])}enableAudioLogging(){this.privProperties.setProperty(d.SpeechServiceConnection_EnableAudioLogging,"true")}requestWordLevelTimestamps(){this.privProperties.setProperty(d.SpeechServiceResponse_RequestWordLevelTimestamps,"true")}enableDictation(){this.privProperties.setProperty(Ai,"true")}clone(){const e=new Y;return e.privProperties=this.privProperties.clone(),e}get speechSynthesisLanguage(){return this.privProperties.getProperty(d.SpeechServiceConnection_SynthLanguage)}set speechSynthesisLanguage(e){this.privProperties.setProperty(d.SpeechServiceConnection_SynthLanguage,e)}get speechSynthesisVoiceName(){return this.privProperties.getProperty(d.SpeechServiceConnection_SynthVoice)}set speechSynthesisVoiceName(e){this.privProperties.setProperty(d.SpeechServiceConnection_SynthVoice,e)}get speechSynthesisOutputFormat(){return f[this.privProperties.getProperty(d.SpeechServiceConnection_SynthOutputFormat,void 0)]}set speechSynthesisOutputFormat(e){this.privProperties.setProperty(d.SpeechServiceConnection_SynthOutputFormat,f[e])}}class ee{constructor(){this.privKeys=[],this.privValues=[]}getProperty(e,t){let r;typeof e=="string"?r=e:r=d[e];for(let n=0;n<this.privKeys.length;n++)if(this.privKeys[n]===r)return this.privValues[n];if(t!==void 0)return String(t)}setProperty(e,t){let r;typeof e=="string"?r=e:r=d[e];for(let n=0;n<this.privKeys.length;n++)if(this.privKeys[n]===r){this.privValues[n]=t;return}this.privKeys.push(r),this.privValues.push(t)}clone(){const e=new ee;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 r=this.getProperty(t);e.setProperty(t,r)}})}get keys(){return this.privKeys}}var d;(function(i){i[i.SpeechServiceConnection_Key=0]="SpeechServiceConnection_Key",i[i.SpeechServiceConnection_Endpoint=1]="SpeechServiceConnection_Endpoint",i[i.SpeechServiceConnection_Region=2]="SpeechServiceConnection_Region",i[i.SpeechServiceAuthorization_Token=3]="SpeechServiceAuthorization_Token",i[i.SpeechServiceAuthorization_Type=4]="SpeechServiceAuthorization_Type",i[i.SpeechServiceConnection_EndpointId=5]="SpeechServiceConnection_EndpointId",i[i.SpeechServiceConnection_TranslationToLanguages=6]="SpeechServiceConnection_TranslationToLanguages",i[i.SpeechServiceConnection_TranslationVoice=7]="SpeechServiceConnection_TranslationVoice",i[i.SpeechServiceConnection_TranslationFeatures=8]="SpeechServiceConnection_TranslationFeatures",i[i.SpeechServiceConnection_IntentRegion=9]="SpeechServiceConnection_IntentRegion",i[i.SpeechServiceConnection_ProxyHostName=10]="SpeechServiceConnection_ProxyHostName",i[i.SpeechServiceConnection_ProxyPort=11]="SpeechServiceConnection_ProxyPort",i[i.SpeechServiceConnection_ProxyUserName=12]="SpeechServiceConnection_ProxyUserName",i[i.SpeechServiceConnection_ProxyPassword=13]="SpeechServiceConnection_ProxyPassword",i[i.SpeechServiceConnection_RecoMode=14]="SpeechServiceConnection_RecoMode",i[i.SpeechServiceConnection_RecoLanguage=15]="SpeechServiceConnection_RecoLanguage",i[i.Speech_SessionId=16]="Speech_SessionId",i[i.SpeechServiceConnection_SynthLanguage=17]="SpeechServiceConnection_SynthLanguage",i[i.SpeechServiceConnection_SynthVoice=18]="SpeechServiceConnection_SynthVoice",i[i.SpeechServiceConnection_SynthOutputFormat=19]="SpeechServiceConnection_SynthOutputFormat",i[i.SpeechServiceConnection_AutoDetectSourceLanguages=20]="SpeechServiceConnection_AutoDetectSourceLanguages",i[i.SpeechServiceResponse_RequestDetailedResultTrueFalse=21]="SpeechServiceResponse_RequestDetailedResultTrueFalse",i[i.SpeechServiceResponse_RequestProfanityFilterTrueFalse=22]="SpeechServiceResponse_RequestProfanityFilterTrueFalse",i[i.SpeechServiceResponse_JsonResult=23]="SpeechServiceResponse_JsonResult",i[i.SpeechServiceResponse_JsonErrorDetails=24]="SpeechServiceResponse_JsonErrorDetails",i[i.CancellationDetails_Reason=25]="CancellationDetails_Reason",i[i.CancellationDetails_ReasonText=26]="CancellationDetails_ReasonText",i[i.CancellationDetails_ReasonDetailedText=27]="CancellationDetails_ReasonDetailedText",i[i.LanguageUnderstandingServiceResponse_JsonResult=28]="LanguageUnderstandingServiceResponse_JsonResult",i[i.SpeechServiceConnection_Url=29]="SpeechServiceConnection_Url",i[i.SpeechServiceConnection_InitialSilenceTimeoutMs=30]="SpeechServiceConnection_InitialSilenceTimeoutMs",i[i.SpeechServiceConnection_EndSilenceTimeoutMs=31]="SpeechServiceConnection_EndSilenceTimeoutMs",i[i.Speech_SegmentationSilenceTimeoutMs=32]="Speech_SegmentationSilenceTimeoutMs",i[i.SpeechServiceConnection_EnableAudioLogging=33]="SpeechServiceConnection_EnableAudioLogging",i[i.SpeechServiceConnection_AtStartLanguageIdPriority=34]="SpeechServiceConnection_AtStartLanguageIdPriority",i[i.SpeechServiceConnection_ContinuousLanguageIdPriority=35]="SpeechServiceConnection_ContinuousLanguageIdPriority",i[i.SpeechServiceConnection_RecognitionEndpointVersion=36]="SpeechServiceConnection_RecognitionEndpointVersion",i[i.SpeechServiceResponse_ProfanityOption=37]="SpeechServiceResponse_ProfanityOption",i[i.SpeechServiceResponse_PostProcessingOption=38]="SpeechServiceResponse_PostProcessingOption",i[i.SpeechServiceResponse_RequestWordLevelTimestamps=39]="SpeechServiceResponse_RequestWordLevelTimestamps",i[i.SpeechServiceResponse_StablePartialResultThreshold=40]="SpeechServiceResponse_StablePartialResultThreshold",i[i.SpeechServiceResponse_OutputFormatOption=41]="SpeechServiceResponse_OutputFormatOption",i[i.SpeechServiceResponse_TranslationRequestStablePartialResult=42]="SpeechServiceResponse_TranslationRequestStablePartialResult",i[i.SpeechServiceResponse_RequestWordBoundary=43]="SpeechServiceResponse_RequestWordBoundary",i[i.SpeechServiceResponse_RequestPunctuationBoundary=44]="SpeechServiceResponse_RequestPunctuationBoundary",i[i.SpeechServiceResponse_RequestSentenceBoundary=45]="SpeechServiceResponse_RequestSentenceBoundary",i[i.Conversation_ApplicationId=46]="Conversation_ApplicationId",i[i.Conversation_DialogType=47]="Conversation_DialogType",i[i.Conversation_Initial_Silence_Timeout=48]="Conversation_Initial_Silence_Timeout",i[i.Conversation_From_Id=49]="Conversation_From_Id",i[i.Conversation_Conversation_Id=50]="Conversation_Conversation_Id",i[i.Conversation_Custom_Voice_Deployment_Ids=51]="Conversation_Custom_Voice_Deployment_Ids",i[i.Conversation_Speech_Activity_Template=52]="Conversation_Speech_Activity_Template",i[i.Conversation_Request_Bot_Status_Messages=53]="Conversation_Request_Bot_Status_Messages",i[i.Conversation_Agent_Connection_Id=54]="Conversation_Agent_Connection_Id",i[i.SpeechServiceConnection_Host=55]="SpeechServiceConnection_Host",i[i.ConversationTranslator_Host=56]="ConversationTranslator_Host",i[i.ConversationTranslator_Name=57]="ConversationTranslator_Name",i[i.ConversationTranslator_CorrelationId=58]="ConversationTranslator_CorrelationId",i[i.ConversationTranslator_Token=59]="ConversationTranslator_Token",i[i.PronunciationAssessment_ReferenceText=60]="PronunciationAssessment_ReferenceText",i[i.PronunciationAssessment_GradingSystem=61]="PronunciationAssessment_GradingSystem",i[i.PronunciationAssessment_Granularity=62]="PronunciationAssessment_Granularity",i[i.PronunciationAssessment_EnableMiscue=63]="PronunciationAssessment_EnableMiscue",i[i.PronunciationAssessment_Json=64]="PronunciationAssessment_Json",i[i.PronunciationAssessment_Params=65]="PronunciationAssessment_Params",i[i.SpeakerRecognition_Api_Version=66]="SpeakerRecognition_Api_Version"})(d||(d={}));var te;(function(i){i[i.NoError=0]="NoError",i[i.AuthenticationFailure=1]="AuthenticationFailure",i[i.BadRequestParameters=2]="BadRequestParameters",i[i.TooManyRequests=3]="TooManyRequests",i[i.ConnectionFailure=4]="ConnectionFailure",i[i.ServiceTimeout=5]="ServiceTimeout",i[i.ServiceError=6]="ServiceError",i[i.RuntimeError=7]="RuntimeError",i[i.Forbidden=8]="Forbidden"})(te||(te={}));class m{}m.BotId="botid",m.CustomSpeechDeploymentId="cid",m.CustomVoiceDeploymentId="deploymentId",m.EnableAudioLogging="storeAudio",m.EnableLanguageId="lidEnabled",m.EnableWordLevelTimestamps="wordLevelTimestamps",m.EndSilenceTimeoutMs="endSilenceTimeoutMs",m.SegmentationSilenceTimeoutMs="segmentationSilenceTimeoutMs",m.Format="format",m.InitialSilenceTimeoutMs="initialSilenceTimeoutMs",m.Language="language",m.Profanity="profanity",m.RequestBotStatusMessages="enableBotMessageStatus",m.StableIntermediateThreshold="stableIntermediateThreshold",m.StableTranslation="stableTranslation",m.TestHooks="testhooks",m.Postprocessing="postprocessing";class ft{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,r){new Map([[d.Speech_SegmentationSilenceTimeoutMs,m.SegmentationSilenceTimeoutMs],[d.SpeechServiceConnection_EnableAudioLogging,m.EnableAudioLogging],[d.SpeechServiceConnection_EndSilenceTimeoutMs,m.EndSilenceTimeoutMs],[d.SpeechServiceConnection_InitialSilenceTimeoutMs,m.InitialSilenceTimeoutMs],[d.SpeechServiceResponse_PostProcessingOption,m.Postprocessing],[d.SpeechServiceResponse_ProfanityOption,m.Profanity],[d.SpeechServiceResponse_RequestWordLevelTimestamps,m.EnableWordLevelTimestamps],[d.SpeechServiceResponse_StablePartialResultThreshold,m.StableIntermediateThreshold]]).forEach((o,a)=>{this.setUrlParameter(a,o,e,t,r)});const s=JSON.parse(e.parameters.getProperty(Fe,"{}"));Object.keys(s).forEach(o=>{t[o]=s[o]})}setUrlParameter(e,t,r,n,s){const o=r.parameters.getProperty(e,void 0);o&&(!s||s.search(t)===-1)&&(n[t]=o.toLocaleLowerCase())}}var Ue;(function(i){i[i.Masked=0]="Masked",i[i.Removed=1]="Removed",i[i.Raw=2]="Raw"})(Ue||(Ue={}));var be=globalThis&&globalThis.__awaiter||function(i,e,t,r){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(h){try{c(r.next(h))}catch(p){o(p)}}function u(h){try{c(r.throw(h))}catch(p){o(p)}}function c(h){h.done?s(h.value):n(h.value).then(a,u)}c((r=r.apply(i,e||[])).next())})};class Ee{constructor(e,t){const r=e;C.throwIfNull(r,"speechConfig"),t!==null&&(t===void 0?this.audioConfig=typeof window=="undefined"?void 0:Q.fromDefaultSpeakerOutput():this.audioConfig=t),this.privProperties=r.properties.clone(),this.privDisposed=!1,this.privSynthesizing=!1,this.privConnectionFactory=new fi,this.synthesisRequestQueue=new he,this.implCommonSynthesizeSetup()}get authorizationToken(){return this.properties.getProperty(d.SpeechServiceAuthorization_Token)}set authorizationToken(e){C.throwIfNullOrWhitespace(e,"token"),this.properties.setProperty(d.SpeechServiceAuthorization_Token,e)}get properties(){return this.privProperties}get autoDetectSourceLanguage(){return this.properties.getProperty(d.SpeechServiceConnection_AutoDetectSourceLanguages)===Pi}static FromConfig(e,t,r){const n=e;return t.properties.mergeTo(n.properties),new Ee(e,r)}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 r=this.properties.getProperty(d.SpeechServiceConnection_SynthLanguage,"en-US"),n=this.properties.getProperty(d.SpeechServiceConnection_SynthVoice,""),s=Ee.XMLEncode(e);return this.autoDetectSourceLanguage?r="en-US":n=n||t[r],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='${r}'>${s}</speak>`,s}speakTextAsync(e,t,r,n){this.speakImpl(e,!1,t,r,n)}speakSsmlAsync(e,t,r,n){this.speakImpl(e,!0,t,r,n)}getVoicesAsync(e=""){return be(this,void 0,void 0,function*(){return this.getVoices(e)})}close(e,t){C.throwIfDisposed(this.privDisposed),Kt(this.dispose(!0),e,t)}get internalData(){return this.privAdapter}dispose(e){return be(this,void 0,void 0,function*(){this.privDisposed||(e&&this.privAdapter&&(yield this.privAdapter.dispose()),this.privDisposed=!0)})}createSynthesizerConfig(e){return new yi(e,this.privProperties)}createSynthesisAdapter(e,t,r,n){return new ne(e,t,n,this,this.audioConfig)}implCommonSynthesizeSetup(){let e=typeof window!="undefined"?"Browser":"Node",t="unknown",r="unknown";typeof navigator!="undefined"&&(e=e+"/"+navigator.platform,t=navigator.userAgent,r=navigator.appVersion);const n=this.createSynthesizerConfig(new yt(new bt(new vi(e,t,r)))),s=this.privProperties.getProperty(d.SpeechServiceConnection_Key,void 0),o=s&&s!==""?new ii(s):new ue(()=>{const a=this.privProperties.getProperty(d.SpeechServiceAuthorization_Token,void 0);return Promise.resolve(a)},()=>{const a=this.privProperties.getProperty(d.SpeechServiceAuthorization_Token,void 0);return Promise.resolve(a)});this.privAdapter=this.createSynthesisAdapter(o,this.privConnectionFactory,this.audioConfig,n),this.privAdapter.audioOutputFormat=l.fromSpeechSynthesisOutputFormat(f[this.properties.getProperty(d.SpeechServiceConnection_SynthOutputFormat,void 0)]),this.privRestAdapter=new Ci(n)}speakImpl(e,t,r,n,s){try{C.throwIfDisposed(this.privDisposed);const o=E();let a;s instanceof vt?a=new He(s):s instanceof Ce?a=s:s!==void 0?a=new at(s):a=void 0,this.synthesisRequestQueue.enqueue(new oi(o,e,t,u=>{if(this.privSynthesizing=!1,r)try{r(u)}catch(c){n&&n(c)}r=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 be(this,void 0,void 0,function*(){const t=E(),r=yield this.privRestAdapter.getVoicesList(t);if(r.ok&&Array.isArray(r.json)){let n=r.json;return!!e&&e.length>0&&(n=n.filter(s=>!!s.Locale&&s.Locale.toLowerCase()===e.toLowerCase())),new St(t,n,void 0)}else return new St(t,void 0,`Error: ${r.status}: ${r.statusText}`)})}adapterSpeak(){return be(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 oi{constructor(e,t,r,n,s,o){this.requestId=e,this.text=t,this.isSSML=r,this.cb=n,this.err=s,this.dataStream=o}}class mt{constructor(e,t,r,n){this.privResultId=e,this.privReason=t,this.privErrorDetails=r,this.privProperties=n}get resultId(){return this.privResultId}get reason(){return this.privReason}get errorDetails(){return this.privErrorDetails}get properties(){return this.privProperties}}class Ae extends mt{constructor(e,t,r,n,s,o){super(e,t,n,s),this.privAudioData=r,this.privAudioDuration=o}get audioData(){return this.privAudioData}get audioDuration(){return this.privAudioDuration}}class Pe{constructor(e){this.privResult=e}get result(){return this.privResult}}class ai{constructor(e,t,r,n,s,o){this.privAudioOffset=e,this.privDuration=t,this.privText=r,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 hi{constructor(e,t){this.privAudioOffset=e,this.privText=t}get audioOffset(){return this.privAudioOffset}get text(){return this.privText}}class ci{constructor(e,t,r){this.privAudioOffset=e,this.privVisemeId=t,this.privAnimation=r}get audioOffset(){return this.privAudioOffset}get visemeId(){return this.privVisemeId}get animation(){return this.privAnimation}}class St extends mt{constructor(e,t,r){if(Array.isArray(t)){super(e,W.VoicesListRetrieved,void 0,new ee),this.privVoices=[];for(const n of t)this.privVoices.push(new ui(n))}else super(e,W.Canceled,r||"Error information unavailable",new ee)}get voices(){return this.privVoices}}var de;(function(i){i[i.Unknown=0]="Unknown",i[i.Female=1]="Female",i[i.Male=2]="Male"})(de||(de={}));var Me;(function(i){i[i.OnlineNeural=1]="OnlineNeural",i[i.OnlineStandard=2]="OnlineStandard",i[i.OfflineNeural=3]="OfflineNeural",i[i.OfflineStandard=4]="OfflineStandard"})(Me||(Me={}));class ui{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")?Me.OnlineStandard:Me.OnlineNeural,this.privGender=e.Gender==="Male"?de.Male:e.Gender==="Female"?de.Female:de.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 We=globalThis&&globalThis.__awaiter||function(i,e,t,r){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(h){try{c(r.next(h))}catch(p){o(p)}}function u(h){try{c(r.throw(h))}catch(p){o(p)}}function c(h){h.done?s(h.value):n(h.value).then(a,u)}c((r=r.apply(i,e||[])).next())})};const pi=60*30,gt={[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 Ve{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,r){this.privAudioBuffer!==void 0?(this.privAudioBuffer.push(e),this.updateSourceBuffer().then(()=>{t&&t()},n=>{r&&r(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()},r=>{t&&t(r)});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 r=new ArrayBuffer(this.privBytesReceived);this.privAudioOutputStream.read(r).then(()=>{r=ne.addHeader(r,this.privFormat);const n=new Blob([r],{type:gt[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=gt[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=pi,this.privSourceBuffer=this.privMediaSource.addSourceBuffer(t),this.privSourceBuffer.onupdate=()=>{this.updateSourceBuffer().catch(r=>{R.instance.onEvent(new ce(r))})},this.privSourceBuffer.onupdateend=()=>{this.handleSourceBufferUpdateEnd().catch(r=>{R.instance.onEvent(new ce(r))})},this.privSourceBuffer.onupdatestart=()=>{this.privAppendingToBuffer=!1}},this.updateSourceBuffer().catch(r=>{R.instance.onEvent(new ce(r))})):(console.warn(`Format ${v[this.privFormat.formatTag]} could not be played by MSE, streaming playback is not enabled.`),this.privAudioOutputStream=new Ke,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()},r=>{t&&t(r)}),this.privIsPaused=!1)}get internalAudio(){return this.privAudio}updateSourceBuffer(){return We(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 We(this,void 0,void 0,function*(){this.canEndStream()&&this.sourceBufferAvailable()&&(this.privMediaSource.endOfStream(),yield this.notifyPlayback())})}notifyPlayback(){return We(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 j extends xe{constructor(e,t,r,n,s,o,a,u){if(!t)throw new D("path");if(!r)throw new D("requestId");const c={};if(c[y.Path]=t,c[y.RequestId]=r,c[y.RequestTimestamp]=new Date().toISOString(),n&&(c[y.ContentType]=n),o&&(c[y.RequestStreamId]=o),a)for(const h in a)h&&(c[h]=a[h]);u?super(e,s,c,u):super(e,s,c),this.privPath=t,this.privRequestId=r,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,r=null,n=null,s=null;const o={};if(e.headers)for(const a in e.headers)a&&(a.toLowerCase()===y.Path.toLowerCase()?t=e.headers[a]:a.toLowerCase()===y.RequestId.toLowerCase()?r=e.headers[a]:a.toLowerCase()===y.ContentType.toLowerCase()?n=e.headers[a]:a.toLowerCase()===y.RequestStreamId.toLowerCase()?s=e.headers[a]:o[a]=e.headers[a]);return new j(e.messageType,t,r,n,e.body,s,o,e.id)}}var wt;(function(i){i[i.Interactive=0]="Interactive",i[i.Conversation=1]="Conversation",i[i.Dictation=2]="Dictation"})(wt||(wt={}));var Ct;(function(i){i[i.Simple=0]="Simple",i[i.Detailed=1]="Detailed"})(Ct||(Ct={}));class yt{constructor(e){this.context=e}serialize(){return JSON.stringify(this,(e,t)=>{if(t&&typeof t=="object"){const r={};for(const n in t)Object.hasOwnProperty.call(t,n)&&(r[n&&n.charAt(0).toLowerCase()+n.substring(1)]=t[n]);return r}return t})}get Context(){return this.context}get Recognition(){return this.recognition}set Recognition(e){this.recognition=e.toLowerCase()}}class bt{constructor(e){this.system=new di,this.os=e}}class di{constructor(){const e="1.22.0";this.name="SpeechSDK",this.version=e,this.build="JavaScript",this.lang="JavaScript"}}class vi{constructor(e,t,r){this.platform=e,this.name=t,this.version=r}}var ie;(function(i){i.Bluetooth="Bluetooth",i.Wired="Wired",i.WiFi="WiFi",i.Cellular="Cellular",i.InBuilt="InBuilt",i.Unknown="Unknown"})(ie||(ie={}));var re;(function(i){i.Phone="Phone",i.Speaker="Speaker",i.Car="Car",i.Headset="Headset",i.Thermostat="Thermostat",i.Microphones="Microphones",i.Deskphone="Deskphone",i.RemoteControl="RemoteControl",i.Unknown="Unknown",i.File="File",i.Stream="Stream"})(re||(re={}));const Et=`\r
3
+ `;class li{toConnectionMessage(e){const t=new k;try{if(e.messageType===g.Text){const r=e.textContent;let n={},s=null;if(r){const o=r.split(`\r
4
4
  \r
5
- `);o&&o.length>0&&(n=this.parseHeaders(o[0]),o.length>1&&(s=o[1]))}t.resolve(new Be(e.messageType,s,n,e.id))}else if(e.messageType===w.Binary){const r=e.binaryContent;let n={},s=null;if(!r||r.byteLength<2)throw new Error("Invalid binary message format. Header length missing.");const o=new DataView(r),a=o.getInt16(0);if(r.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),r.byteLength>a+2&&(s=r.slice(2+a)),t.resolve(new Be(e.messageType,s,n,e.id))}}catch(r){t.reject(`Error formatting the message. Error: ${r}`)}return t.promise}fromConnectionMessage(e){const t=new T;try{if(e.messageType===w.Text){const r=`${this.makeHeaders(e)}${Et}${e.textBody?e.textBody:""}`;t.resolve(new we(w.Text,r,e.id))}else if(e.messageType===w.Binary){const r=this.makeHeaders(e),n=e.binaryBody,s=this.stringToArrayBuffer(r),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 we(w.Binary,h,e.id))}}catch(r){t.reject(`Error formatting the message. ${r}`)}return t.promise}makeHeaders(e){let t="";if(e.headers)for(const r in e.headers)r&&(t+=`${r}: ${e.headers[r]}${Et}`);return t}parseHeaders(e){const t={};if(e){const r=e.match(/[^\r\n]+/g);if(t){for(const n of r)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),r=new DataView(t);for(let n=0;n<e.length;n++)r.setUint8(n,e.charCodeAt(n));return t}}class fi{constructor(){this.synthesisUri="/cognitiveservices/websocket/v1"}create(e,t,r){let n=e.parameters.getProperty(d.SpeechServiceConnection_Endpoint,void 0);const s=e.parameters.getProperty(d.SpeechServiceConnection_Region,void 0),o=ft.getHostSuffix(s),a=e.parameters.getProperty(d.SpeechServiceConnection_EndpointId,void 0),u=a===void 0?"tts":"voice",h=e.parameters.getProperty(d.SpeechServiceConnection_Host,"wss://"+s+"."+u+".speech"+o),c={};n||(n=h+this.synthesisUri);const p={};t.token!==void 0&&t.token!==""&&(p[t.headerName]=t.token),p[y.ConnectionId]=r,a!==void 0&&(p[m.CustomVoiceDeploymentId]=a),e.parameters.setProperty(d.SpeechServiceConnection_Url,n);const g=e.parameters.getProperty("SPEECH-EnableWebsocketCompression","false")==="true";return new ki(n,c,p,new li,Xe.fromParameters(e.parameters),g,r)}}class mi{toJsonString(){return JSON.stringify(this.iPrivConfig)}get(){return this.iPrivConfig}set(e){this.iPrivConfig=e}}class O{static get requestOptions(){return O.privDefaultRequestOptions}static get configParams(){return O.privDefaultParams}static get restErrors(){return O.privRestErrors}}O.privDefaultRequestOptions={headers:{Accept:"application/json"},ignoreCache:!1,timeout:1e4},O.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."},O.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 _;(function(i){i.WordBoundary="WordBoundary",i.Bookmark="Bookmark",i.Viseme="Viseme",i.SentenceBoundary="SentenceBoundary",i.SessionEnd="SessionEnd"})(_||(_={}));class qe{constructor(e){this.privSynthesisAudioMetadata=JSON.parse(e)}static fromJSON(e){return new qe(e)}get Metadata(){return this.privSynthesisAudioMetadata.Metadata}}var V=globalThis&&globalThis.__awaiter||function(i,e,t,r){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(r.next(c))}catch(p){o(p)}}function u(c){try{h(r.throw(c))}catch(p){o(p)}}function h(c){c.done?s(c.value):n(c.value).then(a,u)}h((r=r.apply(i,e||[])).next())})};class ne{constructor(e,t,r,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 k("authentication");if(!t)throw new k("connectionFactory");if(!r)throw new k("synthesizerConfig");this.privAuthentication=e,this.privConnectionFactory=t,this.privSynthesizerConfig=r,this.privIsDisposed=!1,this.privSpeechSynthesizer=n,this.privSessionAudioDestination=s,this.privSynthesisTurn=new Me,this.privConnectionEvents=new U,this.privServiceEvents=new U,this.privSynthesisContext=new bi(this.privSpeechSynthesizer),this.privAgentConfig=new mi,this.connectionEvents.attach(o=>{if(o.name==="ConnectionClosedEvent"){const a=o;a.statusCode!==1e3&&this.cancelSynthesisLocal(ye.Error,a.statusCode===1007?te.BadRequestParameters:te.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 r=new Uint8Array(e.byteLength+t.header.byteLength);return r.set(new Uint8Array(t.header),0),r.set(new Uint8Array(e),t.header.byteLength),r.buffer}isDisposed(){return this.privIsDisposed}dispose(e){return V(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 V(this,void 0,void 0,function*(){yield this.connectImpl()})}sendNetworkMessage(e,t){return V(this,void 0,void 0,function*(){const r=typeof t=="string"?w.Text:w.Binary,n=typeof t=="string"?"application/json":"";return(yield this.fetchConnection()).send(new j(r,e,this.privSynthesisTurn.requestId,n,t))})}Speak(e,t,r,n,s,o){return V(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,r,n,s);this.privSuccessCallback=n,this.privErrorCallback=s,this.privSynthesisTurn.startNewSynthesis(r,e,t,o);try{yield this.connectImpl();const u=yield this.fetchConnection();yield this.sendSynthesisContext(u),yield this.sendSsmlMessage(u,a,r);const h=new Pe(new Ae(r,W.SynthesizingAudioStarted));this.privSpeechSynthesizer.synthesisStarted&&this.privSpeechSynthesizer.synthesisStarted(this.privSpeechSynthesizer,h),this.receiveMessage()}catch(u){return this.cancelSynthesisLocal(ye.Error,te.ConnectionFailure,u),Promise.reject(u)}})}cancelSynthesis(e,t,r,n){const s=new ee;s.setProperty(Ei,te[r]);const o=new Ae(e,W.Canceled,void 0,n,s);if(this.privSpeechSynthesizer.SynthesisCanceled){const a=new Pe(o);try{this.privSpeechSynthesizer.SynthesisCanceled(this.privSpeechSynthesizer,a)}catch{}}if(this.privSuccessCallback)try{this.privSuccessCallback(o)}catch{}}cancelSynthesisLocal(e,t,r){this.privSynthesisTurn.isSynthesizing&&(this.privSynthesisTurn.onStopSynthesizing(),this.cancelSynthesis(this.privSynthesisTurn.requestId,e,t,r))}processTypeSpecificMessages(e){return!0}receiveMessage(){return V(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 r=j.fromConnectionMessage(t);if(r.requestId.toLowerCase()===this.privSynthesisTurn.requestId.toLowerCase())switch(r.path.toLowerCase()){case"turn.start":this.privSynthesisTurn.onServiceTurnStartResponse();break;case"response":this.privSynthesisTurn.onServiceResponseMessage(r.textBody);break;case"audio":if(this.privSynthesisTurn.streamId.toLowerCase()===r.streamId.toLowerCase()&&!!r.binaryBody){if(this.privSynthesisTurn.onAudioChunkReceived(r.binaryBody),this.privSpeechSynthesizer.synthesizing)try{const o=ne.addHeader(r.binaryBody,this.privSynthesisTurn.audioOutputFormat),a=new Pe(new Ae(this.privSynthesisTurn.requestId,W.SynthesizingAudio,o));this.privSpeechSynthesizer.synthesizing(this.privSpeechSynthesizer,a)}catch{}this.privSessionAudioDestination!==void 0&&this.privSessionAudioDestination.write(r.binaryBody)}break;case"audio.metadata":const n=qe.fromJSON(r.textBody).Metadata;for(const o of n)switch(o.Type){case _.WordBoundary:case _.SentenceBoundary:this.privSynthesisTurn.onTextBoundaryEvent(o);const a=new ai(o.Data.Offset,o.Data.Duration,o.Data.text.Text,o.Data.text.Length,o.Type===_.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 _.Bookmark:const u=new ci(o.Data.Offset,o.Data.Bookmark);if(this.privSpeechSynthesizer.bookmarkReached)try{this.privSpeechSynthesizer.bookmarkReached(this.privSpeechSynthesizer,u)}catch{}break;case _.Viseme:if(this.privSynthesisTurn.onVisemeMetadataReceived(o),o.Data.IsLastAnimation){const h=new hi(o.Data.Offset,o.Data.VisemeId,this.privSynthesisTurn.getAndClearVisemeAnimation());if(this.privSpeechSynthesizer.visemeReceived)try{this.privSpeechSynthesizer.visemeReceived(this.privSpeechSynthesizer,h)}catch{}}break;case _.SessionEnd:this.privSynthesisTurn.onSessionEnd(o);break}break;case"turn.end":this.privSynthesisTurn.onServiceTurnEndResponse();let s;try{const o=yield this.privSynthesisTurn.getAllReceivedAudioWithHeader();s=new Ae(this.privSynthesisTurn.requestId,W.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 Pe(s))}catch{}break;default:this.processTypeSpecificMessages(r)||this.privServiceEvents&&this.serviceEvents.onEvent(new Bt(r.path.toLowerCase(),r.textBody))}return this.receiveMessage()}catch{}})}sendSynthesisContext(e){const t=this.synthesisContext.toJSON();if(t)return e.send(new j(w.Text,"synthesis.context",this.privSynthesisTurn.requestId,"application/json",t))}connectImpl(e=!1){if(this.privConnectionPromise!=null)return this.privConnectionPromise.then(r=>r.state()===P.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(r=>V(this,void 0,void 0,function*(){this.privSynthesisTurn.onAuthCompleted(!1);const n=this.privConnectionFactory.create(this.privSynthesizerConfig,r,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(d.SpeechServiceConnection_Endpoint)} Reason: ${s.reason}`))}),r=>{throw this.privSynthesisTurn.onAuthCompleted(!0),new Error(r)}),this.privConnectionPromise.catch(()=>{}),this.privConnectionPromise}sendSpeechServiceConfig(e,t){if(t)return e.send(new j(w.Text,"speech.config",this.privSynthesisTurn.requestId,"application/json",t))}sendSsmlMessage(e,t,r){return e.send(new j(w.Text,"ssml",r,"application/ssml+xml",t))}fetchConnection(){return V(this,void 0,void 0,function*(){return this.privConnectionConfigurationPromise!==void 0?this.privConnectionConfigurationPromise.then(e=>e.state()===P.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 V(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 je extends F{constructor(e,t,r=S.Info){super(e,r),this.privRequestId=t}get requestId(){return this.privRequestId}}class Si extends je{constructor(e,t,r){super("SynthesisTriggeredEvent",e),this.privSessionAudioDestinationId=t,this.privTurnAudioDestinationId=r}get audioSessionDestinationId(){return this.privSessionAudioDestinationId}get audioTurnDestinationId(){return this.privTurnAudioDestinationId}}class wi extends je{constructor(e,t){super("ConnectingToSynthesisServiceEvent",e),this.privAuthFetchEventId=t}get authFetchEventId(){return this.privAuthFetchEventId}}class gi extends je{constructor(e,t){super("SynthesisStartedEvent",e),this.privAuthFetchEventId=t}get authFetchEventId(){return this.privAuthFetchEventId}}var Ge=globalThis&&globalThis.__awaiter||function(i,e,t,r){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(r.next(c))}catch(p){o(p)}}function u(c){try{h(r.throw(c))}catch(p){o(p)}}function h(c){c.done?s(c.value):n(c.value).then(a,u)}h((r=r.apply(i,e||[])).next())})};class Me{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 T,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 Ge(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 Ge(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,r,n){this.privIsSynthesisEnded=!1,this.privIsSynthesizing=!0,this.privRequestId=e,this.privRawText=t,this.privIsSSML=r,this.privAudioOutputStream=new Ke,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 Si(this.requestId,void 0,n===void 0?void 0:n.id()))}onPreConnectionStart(e){this.privAuthFetchEventId=e,this.onEvent(new wi(this.privRequestId,this.privAuthFetchEventId))}onAuthCompleted(e){e&&this.onComplete()}onConnectionEstablishCompleted(e){if(e===200){this.onEvent(new gi(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 T}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){M.instance.onEvent(e)}static isXmlTag(e){return e.length>=2&&e[0]==="<"&&e[e.length-1]===">"}updateTextOffset(e,t){t===_.WordBoundary?(this.privTextOffset=this.privRawText.indexOf(e,this.privNextSearchTextIndex),this.privTextOffset>=0&&(this.privNextSearchTextIndex=this.privTextOffset+e.length,this.privIsSSML&&this.withinXmlTag(this.privTextOffset)&&!Me.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)&&!Me.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 Ge(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 Ci{constructor(e){let t=e.parameters.getProperty(d.SpeechServiceConnection_Endpoint,void 0);if(!t){const n=e.parameters.getProperty(d.SpeechServiceConnection_Region,"westus"),s=ft.getHostSuffix(n);t=e.parameters.getProperty(d.SpeechServiceConnection_Host,`https://${n}.tts.speech${s}`)}this.privUri=`${t}/cognitiveservices/voices/list`;const r=O.requestOptions;r.headers[O.configParams.subscriptionKey]=e.parameters.getProperty(d.SpeechServiceConnection_Key,void 0),this.privRestAdapter=new Ni(r)}getVoicesList(e){return this.privRestAdapter.setHeaders(y.ConnectionId,e),this.privRestAdapter.request(G.Get,this.privUri)}}var $e;(function(i){i[i.Standard=0]="Standard",i[i.Custom=1]="Custom"})($e||($e={}));class yi{constructor(e,t){this.privSynthesisServiceType=$e.Standard,this.privSpeechServiceConfig=e||new yt(new bt(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 bi{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(d.SpeechServiceResponse_RequestPunctuationBoundary,!!this.privSpeechSynthesizer.wordBoundary),sentenceBoundaryEnabled:this.privSpeechSynthesizer.properties.getProperty(d.SpeechServiceResponse_RequestSentenceBoundary,!1),sessionEndEnabled:!0,visemeEnabled:!!this.privSpeechSynthesizer.visemeReceived,wordBoundaryEnabled:this.privSpeechSynthesizer.properties.getProperty(d.SpeechServiceResponse_RequestWordBoundary,!!this.privSpeechSynthesizer.wordBoundary)},outputFormat:this.privAudioOutputFormat.requestAudioFormatString},language:{autoDetection:this.privSpeechSynthesizer.autoDetectSourceLanguage}}}}const At="OutputFormat",Ei="CancellationErrorCode",Fe="ServiceProperties",Ai="ForceDictation",Pi="OpenRange";var Te=globalThis&&globalThis.__awaiter||function(i,e,t,r){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(r.next(c))}catch(p){o(p)}}function u(c){try{h(r.throw(c))}catch(p){o(p)}}function h(c){c.done?s(c.value):n(c.value).then(a,u)}h((r=r.apply(i,e||[])).next())})};const Ri="MICROPHONE-WorkletSourceUrl";class N{constructor(e,t,r,n){this.privRecorder=e,this.deviceId=t,this.privStreams={},this.privOutputChunkSize=N.AUDIOFORMAT.avgBytesPerSec/10,this.privId=r||E(),this.privEvents=new U,this.privMediaStream=n||null,this.privIsClosing=!1}get format(){return Promise.resolve(N.AUDIOFORMAT)}get blob(){return Promise.reject("Not implemented for Mic input")}turnOn(){if(this.privInitializeDeferral)return this.privInitializeDeferral.promise;this.privInitializeDeferral=new T;try{this.createAudioContext()}catch(r){if(r instanceof Error){const n=r;this.privInitializeDeferral.reject(n.name+": "+n.message)}else this.privInitializeDeferral.reject(r);return this.privInitializeDeferral.promise}const e=window.navigator;let t=e.getUserMedia||e.webkitGetUserMedia||e.mozGetUserMedia||e.msGetUserMedia;if(e.mediaDevices&&(t=(r,n,s)=>{e.mediaDevices.getUserMedia(r).then(n).catch(s)}),t){const r=()=>{this.onEvent(new le(this.privId)),this.privMediaStream&&this.privMediaStream.active?(this.onEvent(new oe(this.privId)),this.privInitializeDeferral.resolve()):t({audio:this.deviceId?{deviceId:this.deviceId}:!0,video:!1},n=>{this.privMediaStream=n,this.onEvent(new oe(this.privId)),this.privInitializeDeferral.resolve()},n=>{const s=`Error occurred during microphone initialization: ${n}`;this.privInitializeDeferral.reject(s),this.onEvent(new Ie(this.privId,s))})};this.privContext.state==="suspended"?this.privContext.resume().then(r).catch(n=>{this.privInitializeDeferral.reject(`Failed to initialize audio context: ${n}`)}):r()}else{const r="Browser does not support getUserMedia.";this.privInitializeDeferral.reject(r),this.onEvent(new Ie(r,""))}return this.privInitializeDeferral.promise}id(){return this.privId}attach(e){return this.onEvent(new me(this.privId,e)),this.listen(e).then(t=>(this.onEvent(new Se(this.privId,e)),{detach:()=>Te(this,void 0,void 0,function*(){return t.readEnded(),delete this.privStreams[e],this.onEvent(new K(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 K(this.privId,e)))}turnOff(){return Te(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 Ye(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:N.AUDIOFORMAT.bitsPerSample,channelcount:N.AUDIOFORMAT.channels,connectivity:ie.Unknown,manufacturer:"Speech SDK",model:e,samplerate:N.AUDIOFORMAT.samplesPerSec,type:re.Microphones}))}setProperty(e,t){if(e===Ri)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 r=new T;return navigator.mediaDevices.enumerateDevices().then(n=>{for(const s of n)if(s.deviceId===t){this.privMicrophoneLabel=s.label;break}r.resolve(this.privMicrophoneLabel)},()=>r.resolve(this.privMicrophoneLabel)),r.promise}listen(e){return Te(this,void 0,void 0,function*(){yield this.turnOn();const t=new Ne(this.privOutputChunkSize,e);this.privStreams[e]=t;try{this.privRecorder.record(this.privContext,this.privMediaStream,t)}catch(n){throw this.onEvent(new et(this.privId,e,n)),n}return t})}onEvent(e){this.privEvents.onEvent(e),M.instance.onEvent(e)}createAudioContext(){this.privContext||(this.privContext=H.getAudioContext(N.AUDIOFORMAT.samplesPerSec))}destroyAudioContext(){return Te(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())})}}N.AUDIOFORMAT=ge.getDefaultInputFormat();var Je=globalThis&&globalThis.__awaiter||function(i,e,t,r){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(r.next(c))}catch(p){o(p)}}function u(c){try{h(r.throw(c))}catch(p){o(p)}}function h(c){c.done?s(c.value):n(c.value).then(a,u)}h((r=r.apply(i,e||[])).next())})};class Mi{constructor(e,t,r){this.privStreams={},this.privHeaderEnd=44,this.privId=r||E(),this.privEvents=new U,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 Ie(e,"")),Promise.reject(e)}this.onEvent(new le(this.privId)),this.onEvent(new oe(this.privId))}id(){return this.privId}attach(e){return Je(this,void 0,void 0,function*(){this.onEvent(new me(this.privId,e));const t=yield this.upload(e);return this.onEvent(new Se(this.privId,e)),Promise.resolve({detach:()=>Je(this,void 0,void 0,function*(){t.readEnded(),delete this.privStreams[e],this.onEvent(new K(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 K(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 Ye(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:ie.Unknown,manufacturer:"Speech SDK",model:"File",samplerate:e.samplesPerSec,type:re.File}))}readHeader(){const t=this.privSource.slice(0,512),r=new T,n=s=>{const o=new DataView(s),a=z=>String.fromCharCode(o.getUint8(z),o.getUint8(z+1),o.getUint8(z+2),o.getUint8(z+3));if(a(0)!=="RIFF"){r.reject("Invalid WAV header in file, RIFF was not found");return}if(a(8)!=="WAVE"||a(12)!=="fmt "){r.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),p=o.getUint16(34,!0);let g=36+Math.max(u-16,0);for(;a(g)!=="data";g+=2)if(g>512-8){r.reject("Invalid WAV header in file, data block was not found");return}this.privHeaderEnd=g+8,r.resolve(ge.getWaveFormatPCM(c,p,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 r.promise}upload(e){return Je(this,void 0,void 0,function*(){const t=r=>{const n=`Error occurred while processing '${this.privFilename}'. ${r}`;throw this.onEvent(new et(this.privId,e,n)),new Error(n)};try{yield this.turnOn();const r=yield this.privAudioFormatPromise,n=new Ne(r.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(r){t(r)}})}onEvent(e){this.privEvents.onEvent(e),M.instance.onEvent(e)}}class Qe{constructor(e){this.privStopInputOnRelease=e}record(e,t,r){const s=new Ut(e.sampleRate,16e3),o=e.createMediaStreamSource(t);if(!this.privSpeechProcessorScript){const u=`class SP extends AudioWorkletProcessor {
5
+ `);o&&o.length>0&&(n=this.parseHeaders(o[0]),o.length>1&&(s=o[1]))}t.resolve(new xe(e.messageType,s,n,e.id))}else if(e.messageType===g.Binary){const r=e.binaryContent;let n={},s=null;if(!r||r.byteLength<2)throw new Error("Invalid binary message format. Header length missing.");const o=new DataView(r),a=o.getInt16(0);if(r.byteLength<a+2)throw new Error("Invalid binary message format. Header content missing.");let u="";for(let c=0;c<a;c++)u+=String.fromCharCode(o.getInt8(c+2));n=this.parseHeaders(u),r.byteLength>a+2&&(s=r.slice(2+a)),t.resolve(new xe(e.messageType,s,n,e.id))}}catch(r){t.reject(`Error formatting the message. Error: ${r}`)}return t.promise}fromConnectionMessage(e){const t=new k;try{if(e.messageType===g.Text){const r=`${this.makeHeaders(e)}${Et}${e.textBody?e.textBody:""}`;t.resolve(new ge(g.Text,r,e.id))}else if(e.messageType===g.Binary){const r=this.makeHeaders(e),n=e.binaryBody,s=this.stringToArrayBuffer(r),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 h=new Int8Array(n);u.set(h,2+a)}const c=u.buffer;t.resolve(new ge(g.Binary,c,e.id))}}catch(r){t.reject(`Error formatting the message. ${r}`)}return t.promise}makeHeaders(e){let t="";if(e.headers)for(const r in e.headers)r&&(t+=`${r}: ${e.headers[r]}${Et}`);return t}parseHeaders(e){const t={};if(e){const r=e.match(/[^\r\n]+/g);if(t){for(const n of r)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),r=new DataView(t);for(let n=0;n<e.length;n++)r.setUint8(n,e.charCodeAt(n));return t}}class fi{constructor(){this.synthesisUri="/cognitiveservices/websocket/v1"}create(e,t,r){let n=e.parameters.getProperty(d.SpeechServiceConnection_Endpoint,void 0);const s=e.parameters.getProperty(d.SpeechServiceConnection_Region,void 0),o=ft.getHostSuffix(s),a=e.parameters.getProperty(d.SpeechServiceConnection_EndpointId,void 0),u=a===void 0?"tts":"voice",c=e.parameters.getProperty(d.SpeechServiceConnection_Host,"wss://"+s+"."+u+".speech"+o),h={};n||(n=c+this.synthesisUri);const p={};t.token!==void 0&&t.token!==""&&(p[t.headerName]=t.token),p[y.ConnectionId]=r,a!==void 0&&(p[m.CustomVoiceDeploymentId]=a),e.parameters.setProperty(d.SpeechServiceConnection_Url,n);const w=e.parameters.getProperty("SPEECH-EnableWebsocketCompression","false")==="true";return new ki(n,h,p,new li,Xe.fromParameters(e.parameters),w,r)}}class mi{toJsonString(){return JSON.stringify(this.iPrivConfig)}get(){return this.iPrivConfig}set(e){this.iPrivConfig=e}}class O{static get requestOptions(){return O.privDefaultRequestOptions}static get configParams(){return O.privDefaultParams}static get restErrors(){return O.privRestErrors}}O.privDefaultRequestOptions={headers:{Accept:"application/json"},ignoreCache:!1,timeout:1e4},O.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."},O.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 _;(function(i){i.WordBoundary="WordBoundary",i.Bookmark="Bookmark",i.Viseme="Viseme",i.SentenceBoundary="SentenceBoundary",i.SessionEnd="SessionEnd"})(_||(_={}));class qe{constructor(e){this.privSynthesisAudioMetadata=JSON.parse(e)}static fromJSON(e){return new qe(e)}get Metadata(){return this.privSynthesisAudioMetadata.Metadata}}var V=globalThis&&globalThis.__awaiter||function(i,e,t,r){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(h){try{c(r.next(h))}catch(p){o(p)}}function u(h){try{c(r.throw(h))}catch(p){o(p)}}function c(h){h.done?s(h.value):n(h.value).then(a,u)}c((r=r.apply(i,e||[])).next())})};class ne{constructor(e,t,r,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 D("authentication");if(!t)throw new D("connectionFactory");if(!r)throw new D("synthesizerConfig");this.privAuthentication=e,this.privConnectionFactory=t,this.privSynthesizerConfig=r,this.privIsDisposed=!1,this.privSpeechSynthesizer=n,this.privSessionAudioDestination=s,this.privSynthesisTurn=new Te,this.privConnectionEvents=new H,this.privServiceEvents=new H,this.privSynthesisContext=new bi(this.privSpeechSynthesizer),this.privAgentConfig=new mi,this.connectionEvents.attach(o=>{if(o.name==="ConnectionClosedEvent"){const a=o;a.statusCode!==1e3&&this.cancelSynthesisLocal(ye.Error,a.statusCode===1007?te.BadRequestParameters:te.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 r=new Uint8Array(e.byteLength+t.header.byteLength);return r.set(new Uint8Array(t.header),0),r.set(new Uint8Array(e),t.header.byteLength),r.buffer}isDisposed(){return this.privIsDisposed}dispose(e){return V(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 V(this,void 0,void 0,function*(){yield this.connectImpl()})}sendNetworkMessage(e,t){return V(this,void 0,void 0,function*(){const r=typeof t=="string"?g.Text:g.Binary,n=typeof t=="string"?"application/json":"";return(yield this.fetchConnection()).send(new j(r,e,this.privSynthesisTurn.requestId,n,t))})}Speak(e,t,r,n,s,o){return V(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,r,n,s);this.privSuccessCallback=n,this.privErrorCallback=s,this.privSynthesisTurn.startNewSynthesis(r,e,t,o);try{yield this.connectImpl();const u=yield this.fetchConnection();yield this.sendSynthesisContext(u),yield this.sendSsmlMessage(u,a,r);const c=new Pe(new Ae(r,W.SynthesizingAudioStarted));this.privSpeechSynthesizer.synthesisStarted&&this.privSpeechSynthesizer.synthesisStarted(this.privSpeechSynthesizer,c),this.receiveMessage()}catch(u){return this.cancelSynthesisLocal(ye.Error,te.ConnectionFailure,u),Promise.reject(u)}})}cancelSynthesis(e,t,r,n){const s=new ee;s.setProperty(Ei,te[r]);const o=new Ae(e,W.Canceled,void 0,n,s);if(this.privSpeechSynthesizer.SynthesisCanceled){const a=new Pe(o);try{this.privSpeechSynthesizer.SynthesisCanceled(this.privSpeechSynthesizer,a)}catch{}}if(this.privSuccessCallback)try{this.privSuccessCallback(o)}catch{}}cancelSynthesisLocal(e,t,r){this.privSynthesisTurn.isSynthesizing&&(this.privSynthesisTurn.onStopSynthesizing(),this.cancelSynthesis(this.privSynthesisTurn.requestId,e,t,r))}processTypeSpecificMessages(e){return!0}receiveMessage(){return V(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 r=j.fromConnectionMessage(t);if(r.requestId.toLowerCase()===this.privSynthesisTurn.requestId.toLowerCase())switch(r.path.toLowerCase()){case"turn.start":this.privSynthesisTurn.onServiceTurnStartResponse();break;case"response":this.privSynthesisTurn.onServiceResponseMessage(r.textBody);break;case"audio":if(this.privSynthesisTurn.streamId.toLowerCase()===r.streamId.toLowerCase()&&!!r.binaryBody){if(this.privSynthesisTurn.onAudioChunkReceived(r.binaryBody),this.privSpeechSynthesizer.synthesizing)try{const o=ne.addHeader(r.binaryBody,this.privSynthesisTurn.audioOutputFormat),a=new Pe(new Ae(this.privSynthesisTurn.requestId,W.SynthesizingAudio,o));this.privSpeechSynthesizer.synthesizing(this.privSpeechSynthesizer,a)}catch{}this.privSessionAudioDestination!==void 0&&this.privSessionAudioDestination.write(r.binaryBody)}break;case"audio.metadata":const n=qe.fromJSON(r.textBody).Metadata;for(const o of n)switch(o.Type){case _.WordBoundary:case _.SentenceBoundary:this.privSynthesisTurn.onTextBoundaryEvent(o);const a=new ai(o.Data.Offset,o.Data.Duration,o.Data.text.Text,o.Data.text.Length,o.Type===_.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 _.Bookmark:const u=new hi(o.Data.Offset,o.Data.Bookmark);if(this.privSpeechSynthesizer.bookmarkReached)try{this.privSpeechSynthesizer.bookmarkReached(this.privSpeechSynthesizer,u)}catch{}break;case _.Viseme:if(this.privSynthesisTurn.onVisemeMetadataReceived(o),o.Data.IsLastAnimation){const c=new ci(o.Data.Offset,o.Data.VisemeId,this.privSynthesisTurn.getAndClearVisemeAnimation());if(this.privSpeechSynthesizer.visemeReceived)try{this.privSpeechSynthesizer.visemeReceived(this.privSpeechSynthesizer,c)}catch{}}break;case _.SessionEnd:this.privSynthesisTurn.onSessionEnd(o);break}break;case"turn.end":this.privSynthesisTurn.onServiceTurnEndResponse();let s;try{const o=yield this.privSynthesisTurn.getAllReceivedAudioWithHeader();s=new Ae(this.privSynthesisTurn.requestId,W.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 Pe(s))}catch{}break;default:this.processTypeSpecificMessages(r)||this.privServiceEvents&&this.serviceEvents.onEvent(new xt(r.path.toLowerCase(),r.textBody))}return this.receiveMessage()}catch{}})}sendSynthesisContext(e){const t=this.synthesisContext.toJSON();if(t)return e.send(new j(g.Text,"synthesis.context",this.privSynthesisTurn.requestId,"application/json",t))}connectImpl(e=!1){if(this.privConnectionPromise!=null)return this.privConnectionPromise.then(r=>r.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(r=>V(this,void 0,void 0,function*(){this.privSynthesisTurn.onAuthCompleted(!1);const n=this.privConnectionFactory.create(this.privSynthesizerConfig,r,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(d.SpeechServiceConnection_Endpoint)} Reason: ${s.reason}`))}),r=>{throw this.privSynthesisTurn.onAuthCompleted(!0),new Error(r)}),this.privConnectionPromise.catch(()=>{}),this.privConnectionPromise}sendSpeechServiceConfig(e,t){if(t)return e.send(new j(g.Text,"speech.config",this.privSynthesisTurn.requestId,"application/json",t))}sendSsmlMessage(e,t,r){return e.send(new j(g.Text,"ssml",r,"application/ssml+xml",t))}fetchConnection(){return V(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 V(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 je extends F{constructor(e,t,r=S.Info){super(e,r),this.privRequestId=t}get requestId(){return this.privRequestId}}class Si extends je{constructor(e,t,r){super("SynthesisTriggeredEvent",e),this.privSessionAudioDestinationId=t,this.privTurnAudioDestinationId=r}get audioSessionDestinationId(){return this.privSessionAudioDestinationId}get audioTurnDestinationId(){return this.privTurnAudioDestinationId}}class gi extends je{constructor(e,t){super("ConnectingToSynthesisServiceEvent",e),this.privAuthFetchEventId=t}get authFetchEventId(){return this.privAuthFetchEventId}}class wi extends je{constructor(e,t){super("SynthesisStartedEvent",e),this.privAuthFetchEventId=t}get authFetchEventId(){return this.privAuthFetchEventId}}var $e=globalThis&&globalThis.__awaiter||function(i,e,t,r){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(h){try{c(r.next(h))}catch(p){o(p)}}function u(h){try{c(r.throw(h))}catch(p){o(p)}}function c(h){h.done?s(h.value):n(h.value).then(a,u)}c((r=r.apply(i,e||[])).next())})};class Te{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 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 $e(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 $e(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,r,n){this.privIsSynthesisEnded=!1,this.privIsSynthesizing=!0,this.privRequestId=e,this.privRawText=t,this.privIsSSML=r,this.privAudioOutputStream=new Ke,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 Si(this.requestId,void 0,n===void 0?void 0:n.id()))}onPreConnectionStart(e){this.privAuthFetchEventId=e,this.onEvent(new gi(this.privRequestId,this.privAuthFetchEventId))}onAuthCompleted(e){e&&this.onComplete()}onConnectionEstablishCompleted(e){if(e===200){this.onEvent(new wi(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){R.instance.onEvent(e)}static isXmlTag(e){return e.length>=2&&e[0]==="<"&&e[e.length-1]===">"}updateTextOffset(e,t){t===_.WordBoundary?(this.privTextOffset=this.privRawText.indexOf(e,this.privNextSearchTextIndex),this.privTextOffset>=0&&(this.privNextSearchTextIndex=this.privTextOffset+e.length,this.privIsSSML&&this.withinXmlTag(this.privTextOffset)&&!Te.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)&&!Te.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 $e(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 Ci{constructor(e){let t=e.parameters.getProperty(d.SpeechServiceConnection_Endpoint,void 0);if(!t){const n=e.parameters.getProperty(d.SpeechServiceConnection_Region,"westus"),s=ft.getHostSuffix(n);t=e.parameters.getProperty(d.SpeechServiceConnection_Host,`https://${n}.tts.speech${s}`)}this.privUri=`${t}/cognitiveservices/voices/list`;const r=O.requestOptions;r.headers[O.configParams.subscriptionKey]=e.parameters.getProperty(d.SpeechServiceConnection_Key,void 0),this.privRestAdapter=new Ni(r)}getVoicesList(e){return this.privRestAdapter.setHeaders(y.ConnectionId,e),this.privRestAdapter.request($.Get,this.privUri)}}var Ge;(function(i){i[i.Standard=0]="Standard",i[i.Custom=1]="Custom"})(Ge||(Ge={}));class yi{constructor(e,t){this.privSynthesisServiceType=Ge.Standard,this.privSpeechServiceConfig=e||new yt(new bt(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 bi{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(d.SpeechServiceResponse_RequestPunctuationBoundary,!!this.privSpeechSynthesizer.wordBoundary),sentenceBoundaryEnabled:this.privSpeechSynthesizer.properties.getProperty(d.SpeechServiceResponse_RequestSentenceBoundary,!1),sessionEndEnabled:!0,visemeEnabled:!!this.privSpeechSynthesizer.visemeReceived,wordBoundaryEnabled:this.privSpeechSynthesizer.properties.getProperty(d.SpeechServiceResponse_RequestWordBoundary,!!this.privSpeechSynthesizer.wordBoundary)},outputFormat:this.privAudioOutputFormat.requestAudioFormatString},language:{autoDetection:this.privSpeechSynthesizer.autoDetectSourceLanguage}}}}const At="OutputFormat",Ei="CancellationErrorCode",Fe="ServiceProperties",Ai="ForceDictation",Pi="OpenRange";var Re=globalThis&&globalThis.__awaiter||function(i,e,t,r){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(h){try{c(r.next(h))}catch(p){o(p)}}function u(h){try{c(r.throw(h))}catch(p){o(p)}}function c(h){h.done?s(h.value):n(h.value).then(a,u)}c((r=r.apply(i,e||[])).next())})};const Mi="MICROPHONE-WorkletSourceUrl";class N{constructor(e,t,r,n){this.privRecorder=e,this.deviceId=t,this.privStreams={},this.privOutputChunkSize=N.AUDIOFORMAT.avgBytesPerSec/10,this.privId=r||E(),this.privEvents=new H,this.privMediaStream=n||null,this.privIsClosing=!1}get format(){return Promise.resolve(N.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(r){if(r instanceof Error){const n=r;this.privInitializeDeferral.reject(n.name+": "+n.message)}else this.privInitializeDeferral.reject(r);return this.privInitializeDeferral.promise}const e=window.navigator;let t=e.getUserMedia||e.webkitGetUserMedia||e.mozGetUserMedia||e.msGetUserMedia;if(e.mediaDevices&&(t=(r,n,s)=>{e.mediaDevices.getUserMedia(r).then(n).catch(s)}),t){const r=()=>{this.onEvent(new le(this.privId)),this.privMediaStream&&this.privMediaStream.active?(this.onEvent(new oe(this.privId)),this.privInitializeDeferral.resolve()):t({audio:this.deviceId?{deviceId:this.deviceId}:!0,video:!1},n=>{this.privMediaStream=n,this.onEvent(new oe(this.privId)),this.privInitializeDeferral.resolve()},n=>{const s=`Error occurred during microphone initialization: ${n}`;this.privInitializeDeferral.reject(s),this.onEvent(new Ie(this.privId,s))})};this.privContext.state==="suspended"?this.privContext.resume().then(r).catch(n=>{this.privInitializeDeferral.reject(`Failed to initialize audio context: ${n}`)}):r()}else{const r="Browser does not support getUserMedia.";this.privInitializeDeferral.reject(r),this.onEvent(new Ie(r,""))}return this.privInitializeDeferral.promise}id(){return this.privId}attach(e){return this.onEvent(new me(this.privId,e)),this.listen(e).then(t=>(this.onEvent(new Se(this.privId,e)),{detach:()=>Re(this,void 0,void 0,function*(){return t.readEnded(),delete this.privStreams[e],this.onEvent(new K(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 K(this.privId,e)))}turnOff(){return Re(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 Ye(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:N.AUDIOFORMAT.bitsPerSample,channelcount:N.AUDIOFORMAT.channels,connectivity:ie.Unknown,manufacturer:"Speech SDK",model:e,samplerate:N.AUDIOFORMAT.samplesPerSec,type:re.Microphones}))}setProperty(e,t){if(e===Mi)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 r=new k;return navigator.mediaDevices.enumerateDevices().then(n=>{for(const s of n)if(s.deviceId===t){this.privMicrophoneLabel=s.label;break}r.resolve(this.privMicrophoneLabel)},()=>r.resolve(this.privMicrophoneLabel)),r.promise}listen(e){return Re(this,void 0,void 0,function*(){yield this.turnOn();const t=new Ne(this.privOutputChunkSize,e);this.privStreams[e]=t;try{this.privRecorder.record(this.privContext,this.privMediaStream,t)}catch(n){throw this.onEvent(new et(this.privId,e,n)),n}return t})}onEvent(e){this.privEvents.onEvent(e),R.instance.onEvent(e)}createAudioContext(){this.privContext||(this.privContext=U.getAudioContext(N.AUDIOFORMAT.samplesPerSec))}destroyAudioContext(){return Re(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())})}}N.AUDIOFORMAT=we.getDefaultInputFormat();var Je=globalThis&&globalThis.__awaiter||function(i,e,t,r){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(h){try{c(r.next(h))}catch(p){o(p)}}function u(h){try{c(r.throw(h))}catch(p){o(p)}}function c(h){h.done?s(h.value):n(h.value).then(a,u)}c((r=r.apply(i,e||[])).next())})};class Ti{constructor(e,t,r){this.privStreams={},this.privHeaderEnd=44,this.privId=r||E(),this.privEvents=new H,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 Ie(e,"")),Promise.reject(e)}this.onEvent(new le(this.privId)),this.onEvent(new oe(this.privId))}id(){return this.privId}attach(e){return Je(this,void 0,void 0,function*(){this.onEvent(new me(this.privId,e));const t=yield this.upload(e);return this.onEvent(new Se(this.privId,e)),Promise.resolve({detach:()=>Je(this,void 0,void 0,function*(){t.readEnded(),delete this.privStreams[e],this.onEvent(new K(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 K(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 Ye(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:ie.Unknown,manufacturer:"Speech SDK",model:"File",samplerate:e.samplesPerSec,type:re.File}))}readHeader(){const t=this.privSource.slice(0,512),r=new k,n=s=>{const o=new DataView(s),a=x=>String.fromCharCode(o.getUint8(x),o.getUint8(x+1),o.getUint8(x+2),o.getUint8(x+3));if(a(0)!=="RIFF"){r.reject("Invalid WAV header in file, RIFF was not found");return}if(a(8)!=="WAVE"||a(12)!=="fmt "){r.reject("Invalid WAV header in file, WAVEfmt was not found");return}const u=o.getInt32(16,!0),c=o.getUint16(22,!0),h=o.getUint32(24,!0),p=o.getUint16(34,!0);let w=36+Math.max(u-16,0);for(;a(w)!=="data";w+=2)if(w>512-8){r.reject("Invalid WAV header in file, data block was not found");return}this.privHeaderEnd=w+8,r.resolve(we.getWaveFormatPCM(h,p,c))};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 r.promise}upload(e){return Je(this,void 0,void 0,function*(){const t=r=>{const n=`Error occurred while processing '${this.privFilename}'. ${r}`;throw this.onEvent(new et(this.privId,e,n)),new Error(n)};try{yield this.turnOn();const r=yield this.privAudioFormatPromise,n=new Ne(r.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 c=u.target.result;o(c)},a.readAsArrayBuffer(s)}else{const a=s;o(a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength))}return n}catch(r){t(r)}})}onEvent(e){this.privEvents.onEvent(e),R.instance.onEvent(e)}}class Qe{constructor(e){this.privStopInputOnRelease=e}record(e,t,r){const s=new Ht(e.sampleRate,16e3),o=e.createMediaStreamSource(t);if(!this.privSpeechProcessorScript){const u=`class SP extends AudioWorkletProcessor {
6
6
  constructor(options) {
7
7
  super(options);
8
8
  }
@@ -16,4 +16,4 @@ File System access not available, please use Push or PullAudioOutputStream`),thi
16
16
  return true;
17
17
  }
18
18
  }
19
- 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 p=e.sampleRate;for(;h<16384&&p>=32e3;)h<<=1,p>>=1;return e.createScriptProcessor(h,1,1)}})();u.onaudioprocess=h=>{const c=h.inputBuffer.getChannelData(0);if(r&&!r.isClosed){const p=s.encode(c);p&&r.writeStreamChunk({buffer:p,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(r&&!r.isClosed){const p=s.encode(c);p&&r.writeStreamChunk({buffer:p,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 ve=globalThis&&globalThis.__awaiter||function(i,e,t,r){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(r.next(c))}catch(p){o(p)}}function u(c){try{h(r.throw(c))}catch(p){o(p)}}function h(c){c.done?s(c.value):n(c.value).then(a,u)}h((r=r.apply(i,e||[])).next())})};class b{constructor(e){e&&(this.privProxyInfo=e),b.privDiskCache||(b.privDiskCache=new I("microsoft-cognitiveservices-speech-sdk-cache",{supportBuffer:!0,location:typeof process!="undefined"&&!!{}.SPEECH_OCSP_CACHE_ROOT?{}.SPEECH_OCSP_CACHE_ROOT:void 0}))}static forceReinitDiskCache(){b.privDiskCache=void 0,b.privMemCache={}}GetAgent(e){const t=new I.Agent(this.CreateConnection);if(this.privProxyInfo!==void 0&&this.privProxyInfo.HostName!==void 0&&this.privProxyInfo.Port>0){const r="privProxyInfo";t[r]=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 I(t)}static OCSPCheck(e,t){return ve(this,void 0,void 0,function*(){let r,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 Jt),n=c)}),o.on("error",c=>{s||(s=!0,o.destroy(),h(c))}),a.on("secure",()=>ve(this,void 0,void 0,function*(){const c=a.getPeerCertificate(!0);try{const p=yield this.GetIssuer(c);r=(void 0)(c.raw,p.raw);const g=r.id.toString("hex");n||(n=yield b.GetResponseFromCache(g,r,t)),yield this.VerifyOCSPResponse(n,r,t),o.uncork(),s=!0,u(o)}catch(p){o.destroy(),s=!0,h(p)}}))})})}static GetIssuer(e){return e.issuerCertificate?Promise.resolve(e.issuerCertificate):new Promise((t,r)=>{new(void 0)({}).fetchIssuer(e,null,(s,o)=>{if(s){r(s);return}t(o)})})}static GetResponseFromCache(e,t,r){return ve(this,void 0,void 0,function*(){let n=b.privMemCache[e];if(n&&this.onEvent(new Wt(e)),!n)try{const s=yield b.privDiskCache.get(e);s.isCached&&(b.onEvent(new qt(e)),b.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 st(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 Qt(e,h)),n=null;else{const c=Math.min(864e5,(h-u)/2);h-(Date.now()+this.testTimeOffset)<c?(this.onEvent(new Xt(e,u,h)),this.UpdateCache(t,r).catch(p=>{this.onEvent(new ti(e,p.toString()))})):this.onEvent(new Zt(e,u,h))}}catch(s){this.onEvent(new st(e,s)),n=null}return n||this.onEvent(new Vt(e)),n})}static VerifyOCSPResponse(e,t,r){return ve(this,void 0,void 0,function*(){let n=e;return n||(n=yield b.GetOCSPResponse(t,r)),new Promise((s,o)=>{(void 0)({request:t,response:n},a=>{a?(b.onEvent(new Yt(t.id.toString("hex"),a)),e?this.VerifyOCSPResponse(null,t,r).then(()=>{s()},u=>{o(u)}):o(a)):(e||b.StoreCacheEntry(t.id.toString("hex"),n),s())})})})}static UpdateCache(e,t){return ve(this,void 0,void 0,function*(){const r=e.id.toString("hex");this.onEvent(new jt(r));const n=yield this.GetOCSPResponse(e,t);this.StoreCacheEntry(r,n),this.onEvent(new Ft(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 Gt(e))}static StoreDiskCacheEntry(e,t){this.privDiskCache.set(e,t).then(()=>{this.onEvent(new $t(e))})}static GetOCSPResponse(e,t){const r="1.3.6.1.5.5.7.48.1";let n={};if(t){const s=b.GetProxyAgent(t);n.agent=s}return new Promise((s,o)=>{(void 0)(e.cert,r,(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,p)=>{if(c){o(c);return}const g=e.certID;this.onEvent(new ei(g.toString("hex"))),s(p)})})})}static onEvent(e){M.instance.onEvent(e)}CreateConnection(e,t){const r=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:!b.forceDisableOCSPStapling,servername:t.host}),this.privProxyInfo){const o=b.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 r?b.OCSPCheck(n,this.privProxyInfo):n}}b.testTimeOffset=0,b.forceDisableOCSPStapling=!1,b.privMemCache={};var Pt=globalThis&&globalThis.__awaiter||function(i,e,t,r){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(r.next(c))}catch(p){o(p)}}function u(c){try{h(r.throw(c))}catch(p){o(p)}}function h(c){c.done?s(c.value):n(c.value).then(a,u)}h((r=r.apply(i,e||[])).next())})};class ke{constructor(e,t,r,n,s,o){if(!e)throw new k("uri");if(!r)throw new k("messageFormatter");this.proxyInfo=n,this.privConnectionEvents=new U,this.privConnectionId=t,this.privMessageFormatter=r,this.privConnectionState=P.None,this.privUri=e,this.privHeaders=s,this.privEnableCompression=o,this.privHeaders[y.ConnectionId]=this.privConnectionId,this.privLastErrorReceived=""}get state(){return this.privConnectionState}open(){if(this.privConnectionState===P.Disconnected)return Promise.reject(`Cannot open a connection that is in ${this.privConnectionState} state`);if(this.privConnectionEstablishDeferral)return this.privConnectionEstablishDeferral.promise;this.privConnectionEstablishDeferral=new T,this.privCertificateValidatedDeferral=new T,this.privConnectionState=P.Connecting;try{if(typeof WebSocket!="undefined"&&!ke.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 b(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 I(this.privUri,e)}this.privWebsocketClient.binaryType="arraybuffer",this.privReceivingMessageQueue=new ce,this.privDisconnectDeferral=new T,this.privSendMessageQueue=new ce,this.processSendQueue().catch(e=>{M.instance.onEvent(new he(e))})}catch(e){return this.privConnectionEstablishDeferral.resolve(new xe(500,e)),this.privConnectionEstablishDeferral.promise}return this.onEvent(new xt(this.privConnectionId,this.privUri)),this.privWebsocketClient.onopen=()=>{this.privCertificateValidatedDeferral.promise.then(()=>{this.privConnectionState=P.Connected,this.onEvent(new Nt(this.privConnectionId)),this.privConnectionEstablishDeferral.resolve(new xe(200,""))},e=>{this.privConnectionEstablishDeferral.reject(e)})},this.privWebsocketClient.onerror=e=>{this.onEvent(new Ot(this.privConnectionId,e.message,e.type)),this.privLastErrorReceived=e.message},this.privWebsocketClient.onclose=e=>{this.privConnectionState===P.Connecting?(this.privConnectionState=P.Disconnected,this.privConnectionEstablishDeferral.resolve(new xe(e.code,e.reason+" "+this.privLastErrorReceived))):(this.privConnectionState=P.Disconnected,this.privWebsocketClient=null,this.onEvent(new Lt(this.privConnectionId,e.code,e.reason))),this.onClose(e.code,e.reason).catch(t=>{M.instance.onEvent(new he(t))})},this.privWebsocketClient.onmessage=e=>{const t=new Date().toISOString();if(this.privConnectionState===P.Connected){const r=new T;if(this.privReceivingMessageQueue.enqueueFromPromise(r.promise),e.data instanceof ArrayBuffer){const n=new we(w.Binary,e.data);this.privMessageFormatter.toConnectionMessage(n).then(s=>{this.onEvent(new tt(this.privConnectionId,t,s)),r.resolve(s)},s=>{r.reject(`Invalid binary message format. Error: ${s}`)})}else{const n=new we(w.Text,e.data);this.privMessageFormatter.toConnectionMessage(n).then(s=>{this.onEvent(new tt(this.privConnectionId,t,s)),r.resolve(s)},s=>{r.reject(`Invalid text message format. Error: ${s}`)})}}},this.privConnectionEstablishDeferral.promise}send(e){if(this.privConnectionState!==P.Connected)return Promise.reject(`Cannot send on connection that is in ${P[this.privConnectionState]} state`);const t=new T,r=new T;return this.privSendMessageQueue.enqueueFromPromise(r.promise),this.privMessageFormatter.fromConnectionMessage(e).then(n=>{r.resolve({Message:e,RawWebsocketMessage:n,sendStatusDeferral:t})},n=>{r.reject(`Error formatting the message. ${n}`)}),t.promise}read(){return this.privConnectionState!==P.Connected?Promise.reject(`Cannot read on connection that is in ${this.privConnectionState} state`):this.privReceivingMessageQueue.dequeue()}close(e){if(this.privWebsocketClient)this.privConnectionState!==P.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 _t(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 Pt(this,void 0,void 0,function*(){const r=`Connection closed. ${e}: ${t}`;this.privConnectionState=P.Disconnected,this.privDisconnectDeferral.resolve(),yield this.privReceivingMessageQueue.drainAndDispose(()=>{},r),yield this.privSendMessageQueue.drainAndDispose(n=>{n.sendStatusDeferral.reject(r)},r)})}processSendQueue(){return Pt(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(r){t.sendStatusDeferral.reject(r)}}})}onEvent(e){this.privConnectionEvents.onEvent(e),M.instance.onEvent(e)}get isWebsocketOpen(){return this.privWebsocketClient&&this.privWebsocketClient.readyState===this.privWebsocketClient.OPEN}}ke.forceNpmWebSocket=!1;var Ti=globalThis&&globalThis.__awaiter||function(i,e,t,r){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(r.next(c))}catch(p){o(p)}}function u(c){try{h(r.throw(c))}catch(p){o(p)}}function h(c){c.done?s(c.value):n(c.value).then(a,u)}h((r=r.apply(i,e||[])).next())})};class ki{constructor(e,t,r,n,s,o=!1,a){if(this.privIsDisposed=!1,!e)throw new k("uri");if(!n)throw new k("messageFormatter");this.privMessageFormatter=n;let u="",h=0;if(t){for(const c in t)if(c){u+=h===0&&e.indexOf("?")===-1?"?":"&";const p=encodeURIComponent(t[c]);u+=`${c}=${p}`,h++}}if(r){for(const c in r)if(c){u+=h===0&&e.indexOf("?")===-1?"?":"&";const p=encodeURIComponent(r[c]);u+=`${c}=${p}`,h++}}this.privUri=e+u,this.privId=a||E(),this.privConnectionMessageAdapter=new ke(this.privUri,this.id,this.privMessageFormatter,s,r,o)}dispose(){return Ti(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 Xe{constructor(e,t,r,n){this.privProxyHostName=e,this.privProxyPort=t,this.privProxyUserName=r,this.privProxyPassword=n}static fromParameters(e){return new Xe(e.getProperty(d.SpeechServiceConnection_ProxyHostName),parseInt(e.getProperty(d.SpeechServiceConnection_ProxyPort),10),e.getProperty(d.SpeechServiceConnection_ProxyUserName),e.getProperty(d.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 Di=new Set(["json","buffer","string"]);var Ii=i=>(...e)=>{const t=new Set;let r,n,s,o="";return e.forEach(a=>{if(typeof a=="string")if(a.toUpperCase()===a)if(r){const u=`Can't set method to ${a}, already set to ${r}.`;throw new Error(u)}else r=a;else if(a.startsWith("http:")||a.startsWith("https:"))o=a;else if(Di.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}`)}),r||(r="GET"),t.size===0&&t.add(200),i(t,r,n,s,o)};const zi=Ii;class Ze extends Error{constructor(e,...t){super(...t),Error.captureStackTrace&&Error.captureStackTrace(this,Ze),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 r;Object.defineProperty(this,"responseBody",{get:()=>(r||(r=this.arrayBuffer()),r)}),this.headers={};for(const[s,o]of e.headers.entries())this.headers[s.toLowerCase()]=o}}var Bi=zi((i,e,t,r,n)=>async(s,o,a={})=>{s=n+(s||"");let u=new URL(s);if(r||(r={}),u.username&&(r.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),r["Content-Type"]="application/json";else throw new Error("Unknown body type.");a=new Headers({...r||{},...a});const h=await fetch(u,{method:e,headers:a,body:o});if(h.statusCode=h.status,!i.has(h.status))throw new Ze(h);return t==="json"?h.json():t==="buffer"?h.arrayBuffer():t==="string"?h.text():h}),xi=globalThis&&globalThis.__awaiter||function(i,e,t,r){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(r.next(c))}catch(p){o(p)}}function u(c){try{h(r.throw(c))}catch(p){o(p)}}function h(c){c.done?s(c.value):n(c.value).then(a,u)}h((r=r.apply(i,e||[])).next())})},G;(function(i){i.Get="GET",i.Post="POST",i.Delete="DELETE",i.File="file"})(G||(G={}));class Ni{constructor(e){if(!e)throw new k("configParams");this.privHeaders=e.headers,this.privIgnoreCache=e.ignoreCache}static extractHeaderValue(e,t){let r="";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}),r=s[e.toLowerCase()]}catch{}return r}set options(e){this.privHeaders=e.headers,this.privIgnoreCache=e.ignoreCache}setHeaders(e,t){this.privHeaders[e]=t}request(e,t,r={},n=null,s=null){const o=new T,a=e===G.File?"POST":e,u=(p,g={})=>{const z=p;return{data:JSON.stringify(g),headers:JSON.stringify(p.headers),json:g,ok:p.statusCode>=200&&p.statusCode<300,status:p.statusCode,statusText:g.error?g.error.message:z.statusText?z.statusText:z.statusMessage}},h=p=>{const g=new FileReader;return g.readAsArrayBuffer(p),new Promise(z=>{g.onloadend=()=>{z(g.result)}})},c=p=>{const g=Bi(t,a,this.privHeaders,200,201,202,204,400,401,402,403,404),z=this.queryParams(r)===""?"":`?${this.queryParams(r)}`;g(z,p).then($=>xi(this,void 0,void 0,function*(){if(e===G.Delete||$.statusCode===204)o.resolve(u($));else try{const Rt=yield $.json();o.resolve(u($,Rt))}catch{o.resolve(u($))}})).catch($=>{o.reject($)})};if(this.privIgnoreCache&&(this.privHeaders["Cache-Control"]="no-cache"),e===G.File&&s){const p="multipart/form-data";this.privHeaders["content-type"]=p,this.privHeaders["Content-Type"]=p,typeof Blob!="undefined"&&s instanceof Blob?h(s).then(g=>{c(g)}).catch(g=>{o.reject(g)}):c(s)}else e===G.Post&&n&&(this.privHeaders["content-type"]="application/json",this.privHeaders["Content-Type"]="application/json"),c(n);return o.promise}withQuery(e,t={}){const r=this.queryParams(t);return r?e+(e.indexOf("?")===-1?"?":"&")+r:e}queryParams(e={}){return Object.keys(e).map(t=>encodeURIComponent(t)+"="+encodeURIComponent(e[t])).join("&")}}class Li{constructor(e,t,r){B(this,"key");B(this,"region");B(this,"voice");B(this,"textToRead","");B(this,"wordBoundryList",[]);B(this,"clickedNode");B(this,"highlightDiv");B(this,"speechConfig");B(this,"audioConfig");B(this,"player");B(this,"synthesizer");B(this,"previousWordBoundary");this.key=e,this.region=t,this.voice=r}async start(){setInterval(()=>{var e;if(this.player!==void 0&&this.highlightDiv){const t=this.player.currentTime;let r;for(const n of this.wordBoundryList)if(t*1e3>n.audioOffset/1e4)r=n;else break;r!==void 0?(~[".",",","!","?"].indexOf(r.text)&&(r=(e=this.previousWordBoundary)!=null?e:void 0),this.previousWordBoundary=r,this.highlightDiv.innerHTML=this.textToRead.substring(0,r.textOffset)+"<span class='co-tts-highlight'>"+r.text+"</span>"+this.textToRead.substring(r.textOffset+r.wordLength)):this.highlightDiv.innerHTML=this.textToRead}},50),await this.registerBindings(document)}async synthesis(){}async registerBindings(e){const t=e.childNodes;for(let r=0;r<t.length;r++){if(!t[r])continue;const n=t[r];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 r=>{var s;this.stopPlayer(),this.clickedNode=e;const n=document.getElementById(t.value);!n||(n.hasAttribute("co-tts.text")&&n.getAttribute("co-tts.text")!==""?this.textToRead=(s=n.getAttribute("co-tts.text"))!=null?s:"":this.textToRead=n.innerHTML,n.hasAttribute("co-tts.highlight")&&(this.highlightDiv=n),this.startSynthesizer(e,t))})}async handleAjaxModifier(e,t){e.addEventListener("click",async r=>{this.stopPlayer(),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 r=>{this.stopPlayer(),this.clickedNode=e,e.hasAttribute("co-tts.highlight")&&(this.highlightDiv=e),t.value===""?this.textToRead=e.innerHTML:this.textToRead=t.value,this.startSynthesizer(e,t)})}async handleStopModifier(e,t){e.addEventListener("click",async r=>{await this.stopPlayer()})}async handlePauseModifier(e,t){e.addEventListener("click",async r=>{await this.player.pause()})}async handleResumeModifier(e,t){e.addEventListener("click",async r=>{await this.player.resume()})}async stopPlayer(){this.highlightDiv!==void 0&&(this.highlightDiv.innerHTML=this.textToRead),this.textToRead="",this.wordBoundryList=[],this.player!==void 0&&this.player.pause(),this.player=void 0,this.highlightDiv=void 0}async startSynthesizer(e,t){this.speechConfig=lt.fromSubscription(this.key,this.region),this.speechConfig.speechSynthesisVoiceName=`Microsoft Server Speech Text to Speech Voice (${this.voice})`,this.speechConfig.speechSynthesisOutputFormat=8,this.player=new Ve,this.audioConfig=Q.fromSpeakerOutput(this.player),this.synthesizer=new Ee(this.speechConfig,this.audioConfig),this.synthesizer.wordBoundary=(r,n)=>{this.wordBoundryList.push(n)},this.player.onAudioEnd=()=>{if(this.stopPlayer(),this.clickedNode.hasAttribute("co-tts.next")){const r=document.getElementById(this.clickedNode.getAttribute("co-tts.next"));r&&r.dispatchEvent(new Event("click"))}},this.synthesizer.speakTextAsync(this.textToRead,()=>{this.synthesizer.close(),this.synthesizer=void 0},()=>{this.synthesizer.close(),this.synthesizer=void 0})}}return Li});
19
+ registerProcessor('speech-processor', SP);`,c=new Blob([u],{type:"application/javascript; charset=utf-8"});this.privSpeechProcessorScript=URL.createObjectURL(c)}const a=()=>{const u=(()=>{let c=0;try{return e.createScriptProcessor(c,1,1)}catch{c=2048;let p=e.sampleRate;for(;c<16384&&p>=32e3;)c<<=1,p>>=1;return e.createScriptProcessor(c,1,1)}})();u.onaudioprocess=c=>{const h=c.inputBuffer.getChannelData(0);if(r&&!r.isClosed){const p=s.encode(h);p&&r.writeStreamChunk({buffer:p,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=c=>{const h=c.data;if(r&&!r.isClosed){const p=s.encode(h);p&&r.writeStreamChunk({buffer:p,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 ve=globalThis&&globalThis.__awaiter||function(i,e,t,r){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(h){try{c(r.next(h))}catch(p){o(p)}}function u(h){try{c(r.throw(h))}catch(p){o(p)}}function c(h){h.done?s(h.value):n(h.value).then(a,u)}c((r=r.apply(i,e||[])).next())})};class b{constructor(e){e&&(this.privProxyInfo=e),b.privDiskCache||(b.privDiskCache=new z("microsoft-cognitiveservices-speech-sdk-cache",{supportBuffer:!0,location:typeof process!="undefined"&&!!{}.SPEECH_OCSP_CACHE_ROOT?{}.SPEECH_OCSP_CACHE_ROOT:void 0}))}static forceReinitDiskCache(){b.privDiskCache=void 0,b.privMemCache={}}GetAgent(e){const t=new z.Agent(this.CreateConnection);if(this.privProxyInfo!==void 0&&this.privProxyInfo.HostName!==void 0&&this.privProxyInfo.Port>0){const r="privProxyInfo";t[r]=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 z(t)}static OCSPCheck(e,t){return ve(this,void 0,void 0,function*(){let r,n,s=!1;const o=yield e;o.cork();const a=o;return new Promise((u,c)=>{o.on("OCSPResponse",h=>{h&&(this.onEvent(new Jt),n=h)}),o.on("error",h=>{s||(s=!0,o.destroy(),c(h))}),a.on("secure",()=>ve(this,void 0,void 0,function*(){const h=a.getPeerCertificate(!0);try{const p=yield this.GetIssuer(h);r=(void 0)(h.raw,p.raw);const w=r.id.toString("hex");n||(n=yield b.GetResponseFromCache(w,r,t)),yield this.VerifyOCSPResponse(n,r,t),o.uncork(),s=!0,u(o)}catch(p){o.destroy(),s=!0,c(p)}}))})})}static GetIssuer(e){return e.issuerCertificate?Promise.resolve(e.issuerCertificate):new Promise((t,r)=>{new(void 0)({}).fetchIssuer(e,null,(s,o)=>{if(s){r(s);return}t(o)})})}static GetResponseFromCache(e,t,r){return ve(this,void 0,void 0,function*(){let n=b.privMemCache[e];if(n&&this.onEvent(new Wt(e)),!n)try{const s=yield b.privDiskCache.get(e);s.isCached&&(b.onEvent(new qt(e)),b.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 st(e,"Not enough data in cached response"));return}const u=a.responses[0].thisUpdate,c=a.responses[0].nextUpdate;if(c<Date.now()+this.testTimeOffset-6e4)this.onEvent(new Qt(e,c)),n=null;else{const h=Math.min(864e5,(c-u)/2);c-(Date.now()+this.testTimeOffset)<h?(this.onEvent(new Xt(e,u,c)),this.UpdateCache(t,r).catch(p=>{this.onEvent(new ti(e,p.toString()))})):this.onEvent(new Zt(e,u,c))}}catch(s){this.onEvent(new st(e,s)),n=null}return n||this.onEvent(new Vt(e)),n})}static VerifyOCSPResponse(e,t,r){return ve(this,void 0,void 0,function*(){let n=e;return n||(n=yield b.GetOCSPResponse(t,r)),new Promise((s,o)=>{(void 0)({request:t,response:n},a=>{a?(b.onEvent(new Yt(t.id.toString("hex"),a)),e?this.VerifyOCSPResponse(null,t,r).then(()=>{s()},u=>{o(u)}):o(a)):(e||b.StoreCacheEntry(t.id.toString("hex"),n),s())})})})}static UpdateCache(e,t){return ve(this,void 0,void 0,function*(){const r=e.id.toString("hex");this.onEvent(new jt(r));const n=yield this.GetOCSPResponse(e,t);this.StoreCacheEntry(r,n),this.onEvent(new Ft(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 $t(e))}static StoreDiskCacheEntry(e,t){this.privDiskCache.set(e,t).then(()=>{this.onEvent(new Gt(e))})}static GetOCSPResponse(e,t){const r="1.3.6.1.5.5.7.48.1";let n={};if(t){const s=b.GetProxyAgent(t);n.agent=s}return new Promise((s,o)=>{(void 0)(e.cert,r,(a,u)=>{if(a){o(a);return}const c=new URL(u);n=Object.assign(Object.assign({},n),{host:c.host,protocol:c.protocol,port:c.port,path:c.pathname,hostname:c.host}),(void 0)(n,e.data,(h,p)=>{if(h){o(h);return}const w=e.certID;this.onEvent(new ei(w.toString("hex"))),s(p)})})})}static onEvent(e){R.instance.onEvent(e)}CreateConnection(e,t){const r=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:!b.forceDisableOCSPStapling,servername:t.host}),this.privProxyInfo){const o=b.GetProxyAgent(this.privProxyInfo);n=new Promise((a,u)=>{o.callback(e,t,(c,h)=>{c?u(c):a(h)})})}else t.secureEndpoint,n=Promise.resolve((void 0)(t));return r?b.OCSPCheck(n,this.privProxyInfo):n}}b.testTimeOffset=0,b.forceDisableOCSPStapling=!1,b.privMemCache={};var Pt=globalThis&&globalThis.__awaiter||function(i,e,t,r){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(h){try{c(r.next(h))}catch(p){o(p)}}function u(h){try{c(r.throw(h))}catch(p){o(p)}}function c(h){h.done?s(h.value):n(h.value).then(a,u)}c((r=r.apply(i,e||[])).next())})};class ke{constructor(e,t,r,n,s,o){if(!e)throw new D("uri");if(!r)throw new D("messageFormatter");this.proxyInfo=n,this.privConnectionEvents=new H,this.privConnectionId=t,this.privMessageFormatter=r,this.privConnectionState=M.None,this.privUri=e,this.privHeaders=s,this.privEnableCompression=o,this.privHeaders[y.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"&&!ke.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 b(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 z(this.privUri,e)}this.privWebsocketClient.binaryType="arraybuffer",this.privReceivingMessageQueue=new he,this.privDisconnectDeferral=new k,this.privSendMessageQueue=new he,this.processSendQueue().catch(e=>{R.instance.onEvent(new ce(e))})}catch(e){return this.privConnectionEstablishDeferral.resolve(new Be(500,e)),this.privConnectionEstablishDeferral.promise}return this.onEvent(new Bt(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 Be(200,""))},e=>{this.privConnectionEstablishDeferral.reject(e)})},this.privWebsocketClient.onerror=e=>{this.onEvent(new Ot(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 Be(e.code,e.reason+" "+this.privLastErrorReceived))):(this.privConnectionState=M.Disconnected,this.privWebsocketClient=null,this.onEvent(new Lt(this.privConnectionId,e.code,e.reason))),this.onClose(e.code,e.reason).catch(t=>{R.instance.onEvent(new ce(t))})},this.privWebsocketClient.onmessage=e=>{const t=new Date().toISOString();if(this.privConnectionState===M.Connected){const r=new k;if(this.privReceivingMessageQueue.enqueueFromPromise(r.promise),e.data instanceof ArrayBuffer){const n=new ge(g.Binary,e.data);this.privMessageFormatter.toConnectionMessage(n).then(s=>{this.onEvent(new tt(this.privConnectionId,t,s)),r.resolve(s)},s=>{r.reject(`Invalid binary message format. Error: ${s}`)})}else{const n=new ge(g.Text,e.data);this.privMessageFormatter.toConnectionMessage(n).then(s=>{this.onEvent(new tt(this.privConnectionId,t,s)),r.resolve(s)},s=>{r.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,r=new k;return this.privSendMessageQueue.enqueueFromPromise(r.promise),this.privMessageFormatter.fromConnectionMessage(e).then(n=>{r.resolve({Message:e,RawWebsocketMessage:n,sendStatusDeferral:t})},n=>{r.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 _t(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 Pt(this,void 0,void 0,function*(){const r=`Connection closed. ${e}: ${t}`;this.privConnectionState=M.Disconnected,this.privDisconnectDeferral.resolve(),yield this.privReceivingMessageQueue.drainAndDispose(()=>{},r),yield this.privSendMessageQueue.drainAndDispose(n=>{n.sendStatusDeferral.reject(r)},r)})}processSendQueue(){return Pt(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(r){t.sendStatusDeferral.reject(r)}}})}onEvent(e){this.privConnectionEvents.onEvent(e),R.instance.onEvent(e)}get isWebsocketOpen(){return this.privWebsocketClient&&this.privWebsocketClient.readyState===this.privWebsocketClient.OPEN}}ke.forceNpmWebSocket=!1;var Ri=globalThis&&globalThis.__awaiter||function(i,e,t,r){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(h){try{c(r.next(h))}catch(p){o(p)}}function u(h){try{c(r.throw(h))}catch(p){o(p)}}function c(h){h.done?s(h.value):n(h.value).then(a,u)}c((r=r.apply(i,e||[])).next())})};class ki{constructor(e,t,r,n,s,o=!1,a){if(this.privIsDisposed=!1,!e)throw new D("uri");if(!n)throw new D("messageFormatter");this.privMessageFormatter=n;let u="",c=0;if(t){for(const h in t)if(h){u+=c===0&&e.indexOf("?")===-1?"?":"&";const p=encodeURIComponent(t[h]);u+=`${h}=${p}`,c++}}if(r){for(const h in r)if(h){u+=c===0&&e.indexOf("?")===-1?"?":"&";const p=encodeURIComponent(r[h]);u+=`${h}=${p}`,c++}}this.privUri=e+u,this.privId=a||E(),this.privConnectionMessageAdapter=new ke(this.privUri,this.id,this.privMessageFormatter,s,r,o)}dispose(){return Ri(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 Xe{constructor(e,t,r,n){this.privProxyHostName=e,this.privProxyPort=t,this.privProxyUserName=r,this.privProxyPassword=n}static fromParameters(e){return new Xe(e.getProperty(d.SpeechServiceConnection_ProxyHostName),parseInt(e.getProperty(d.SpeechServiceConnection_ProxyPort),10),e.getProperty(d.SpeechServiceConnection_ProxyUserName),e.getProperty(d.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 Di=new Set(["json","buffer","string"]);var Ii=i=>(...e)=>{const t=new Set;let r,n,s,o="";return e.forEach(a=>{if(typeof a=="string")if(a.toUpperCase()===a)if(r){const u=`Can't set method to ${a}, already set to ${r}.`;throw new Error(u)}else r=a;else if(a.startsWith("http:")||a.startsWith("https:"))o=a;else if(Di.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}`)}),r||(r="GET"),t.size===0&&t.add(200),i(t,r,n,s,o)};const zi=Ii;class Ze extends Error{constructor(e,...t){super(...t),Error.captureStackTrace&&Error.captureStackTrace(this,Ze),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 r;Object.defineProperty(this,"responseBody",{get:()=>(r||(r=this.arrayBuffer()),r)}),this.headers={};for(const[s,o]of e.headers.entries())this.headers[s.toLowerCase()]=o}}var xi=zi((i,e,t,r,n)=>async(s,o,a={})=>{s=n+(s||"");let u=new URL(s);if(r||(r={}),u.username&&(r.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),r["Content-Type"]="application/json";else throw new Error("Unknown body type.");a=new Headers({...r||{},...a});const c=await fetch(u,{method:e,headers:a,body:o});if(c.statusCode=c.status,!i.has(c.status))throw new Ze(c);return t==="json"?c.json():t==="buffer"?c.arrayBuffer():t==="string"?c.text():c}),Bi=globalThis&&globalThis.__awaiter||function(i,e,t,r){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(h){try{c(r.next(h))}catch(p){o(p)}}function u(h){try{c(r.throw(h))}catch(p){o(p)}}function c(h){h.done?s(h.value):n(h.value).then(a,u)}c((r=r.apply(i,e||[])).next())})},$;(function(i){i.Get="GET",i.Post="POST",i.Delete="DELETE",i.File="file"})($||($={}));class Ni{constructor(e){if(!e)throw new D("configParams");this.privHeaders=e.headers,this.privIgnoreCache=e.ignoreCache}static extractHeaderValue(e,t){let r="";try{const n=t.trim().split(/[\r\n]+/),s={};n.forEach(o=>{const a=o.split(": "),u=a.shift().toLowerCase(),c=a.join(": ");s[u]=c}),r=s[e.toLowerCase()]}catch{}return r}set options(e){this.privHeaders=e.headers,this.privIgnoreCache=e.ignoreCache}setHeaders(e,t){this.privHeaders[e]=t}request(e,t,r={},n=null,s=null){const o=new k,a=e===$.File?"POST":e,u=(p,w={})=>{const x=p;return{data:JSON.stringify(w),headers:JSON.stringify(p.headers),json:w,ok:p.statusCode>=200&&p.statusCode<300,status:p.statusCode,statusText:w.error?w.error.message:x.statusText?x.statusText:x.statusMessage}},c=p=>{const w=new FileReader;return w.readAsArrayBuffer(p),new Promise(x=>{w.onloadend=()=>{x(w.result)}})},h=p=>{const w=xi(t,a,this.privHeaders,200,201,202,204,400,401,402,403,404),x=this.queryParams(r)===""?"":`?${this.queryParams(r)}`;w(x,p).then(G=>Bi(this,void 0,void 0,function*(){if(e===$.Delete||G.statusCode===204)o.resolve(u(G));else try{const Mt=yield G.json();o.resolve(u(G,Mt))}catch{o.resolve(u(G))}})).catch(G=>{o.reject(G)})};if(this.privIgnoreCache&&(this.privHeaders["Cache-Control"]="no-cache"),e===$.File&&s){const p="multipart/form-data";this.privHeaders["content-type"]=p,this.privHeaders["Content-Type"]=p,typeof Blob!="undefined"&&s instanceof Blob?c(s).then(w=>{h(w)}).catch(w=>{o.reject(w)}):h(s)}else e===$.Post&&n&&(this.privHeaders["content-type"]="application/json",this.privHeaders["Content-Type"]="application/json"),h(n);return o.promise}withQuery(e,t={}){const r=this.queryParams(t);return r?e+(e.indexOf("?")===-1?"?":"&")+r:e}queryParams(e={}){return Object.keys(e).map(t=>encodeURIComponent(t)+"="+encodeURIComponent(e[t])).join("&")}}class Li{constructor(e,t,r){A(this,"key");A(this,"region");A(this,"voice");A(this,"textToRead","");A(this,"wordBoundryList",[]);A(this,"clickedNode");A(this,"highlightDiv");A(this,"speechConfig");A(this,"audioConfig");A(this,"player");A(this,"synthesizer");A(this,"previousWordBoundary");A(this,"interval");A(this,"wordEncounters",[]);A(this,"originalHighlightDivInnerHTML","");A(this,"currentWord","");A(this,"currentOffset",0);this.key=e,this.region=t,this.voice=r}async start(){await this.registerBindings(document)}async registerBindings(e){const t=e.childNodes;for(let r=0;r<t.length;r++){if(!t[r])continue;const n=t[r];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 r=>{var s;this.stopPlayer(),await this.createInterval(),this.clickedNode=e;const n=document.getElementById(t.value);!n||(n.hasAttribute("co-tts.text")&&n.getAttribute("co-tts.text")!==""?this.textToRead=(s=n.getAttribute("co-tts.text"))!=null?s:"":this.textToRead=n.innerHTML,n.hasAttribute("co-tts.highlight")&&(this.highlightDiv=n,this.originalHighlightDivInnerHTML=n.innerHTML),this.startSynthesizer(e,t))})}async handleAjaxModifier(e,t){e.addEventListener("click",async r=>{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 r=>{this.stopPlayer(),await this.createInterval(),this.clickedNode=e,e.hasAttribute("co-tts.highlight")&&(this.highlightDiv=e,this.originalHighlightDivInnerHTML=e.innerHTML),t.value===""?this.textToRead=e.innerHTML:this.textToRead=t.value,this.startSynthesizer(e,t)})}async handleWithoutClick(e,t){this.stopPlayer(),await this.createInterval(),this.clickedNode=e,e.hasAttribute("co-tts.highlight")&&(this.highlightDiv=e,this.originalHighlightDivInnerHTML=e.innerHTML),t.value===""?this.textToRead=e.innerHTML:this.textToRead=t.value,this.startSynthesizer(e,t)}async handleStopModifier(e,t){e.addEventListener("click",async r=>{await this.stopPlayer(),document.dispatchEvent(new CustomEvent("COAzureTTSStoppedPlaying",{}))})}async handlePauseModifier(e,t){e.addEventListener("click",async r=>{await this.clearInterval(),await this.player.pause(),document.dispatchEvent(new CustomEvent("COAzureTTSPausedPlaying",{}))})}async handleResumeModifier(e,t){e.addEventListener("click",async r=>{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.player!==void 0&&this.player.pause(),this.player=void 0,this.highlightDiv=void 0}async startSynthesizer(e,t){this.speechConfig=lt.fromSubscription(this.key,this.region),this.speechConfig.speechSynthesisVoiceName=`Microsoft Server Speech Text to Speech Voice (${this.voice})`,this.speechConfig.speechSynthesisOutputFormat=f.Audio24Khz160KBitRateMonoMp3,this.player=new Ve,this.audioConfig=Q.fromSpeakerOutput(this.player),this.synthesizer=new Ee(this.speechConfig,this.audioConfig),this.synthesizer.wordBoundary=(r,n)=>{this.wordBoundryList.push(n)},this.player.onAudioEnd=async()=>{if(this.stopPlayer(),this.clickedNode.hasAttribute("co-tts.next")){const r=document.getElementById(this.clickedNode.getAttribute("co-tts.next"));r&&r.attributes.getNamedItem("co-tts.text")?this.handleWithoutClick(r,r.attributes.getNamedItem("co-tts.text")):r&&r.dispatchEvent(new Event("click"))}else document.dispatchEvent(new CustomEvent("COAzureTTSFinishedPlaying",{}))},this.player.onAudioStart=async()=>{document.dispatchEvent(new CustomEvent("COAzureTTSStartedPlaying",{}))},this.synthesizer.speakTextAsync(this.textToRead,()=>{this.synthesizer.close(),this.synthesizer=void 0},()=>{this.synthesizer.close(),this.synthesizer=void 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 r;for(const n of this.wordBoundryList)if(t*1e3>n.audioOffset/1e4)r=n;else break;r!==void 0?(~[".",",","!","?"].indexOf(r.text)&&(r=(e=this.previousWordBoundary)!=null?e:void 0),r===void 0?this.highlightDiv.innerHTML=this.originalHighlightDivInnerHTML:(this.wordEncounters[r.text]||(this.wordEncounters[r.text]=0),this.currentWord!==r.text&&(this.wordEncounters[r.text]++,console.log(this.wordEncounters),this.currentOffset=this.getPosition(this.originalHighlightDivInnerHTML,r.text,this.wordEncounters[r.text]),this.currentWord=r.text),this.previousWordBoundary=r,this.highlightDiv.innerHTML=this.originalHighlightDivInnerHTML.substring(0,this.currentOffset)+"<mark class='co-tts-highlight'>"+r.text+"</mark>"+this.originalHighlightDivInnerHTML.substring(this.currentOffset+r.wordLength))):this.highlightDiv.innerHTML=this.originalHighlightDivInnerHTML}},50)}getPosition(e,t,r){const n=new RegExp(`\\b${t}\\b`,"g");return console.log(e.split(n,r).join(t),n,r),e.split(n,r).join(t).length}}return Li});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@creativeorange/azure-text-to-speech",
3
- "version": "1.0.1",
3
+ "version": "1.1.0",
4
4
  "main": "dist/co-azure-tts.umd.js",
5
5
  "browser": "dist/co-azure-tts.es.js",
6
6
  "scripts": {
package/src/main.ts CHANGED
@@ -1,4 +1,10 @@
1
- import {SpeakerAudioDestination, AudioConfig, SpeechConfig, SpeechSynthesizer} from 'microsoft-cognitiveservices-speech-sdk';
1
+ import {
2
+ SpeakerAudioDestination,
3
+ AudioConfig,
4
+ SpeechConfig,
5
+ SpeechSynthesizer,
6
+ SpeechSynthesisOutputFormat,
7
+ } from 'microsoft-cognitiveservices-speech-sdk';
2
8
 
3
9
  export default class TextToSpeech {
4
10
  key: string;
@@ -19,6 +25,13 @@ export default class TextToSpeech {
19
25
 
20
26
  previousWordBoundary: any;
21
27
 
28
+ interval: any;
29
+
30
+ wordEncounters: number[] = [];
31
+ originalHighlightDivInnerHTML: string = '';
32
+ currentWord: string = '';
33
+ currentOffset: number = 0;
34
+
22
35
 
23
36
  constructor(key: string, region: string, voice: string) {
24
37
  this.key = key;
@@ -27,40 +40,9 @@ export default class TextToSpeech {
27
40
  }
28
41
 
29
42
  async start() {
30
- setInterval(() => {
31
- if (this.player !== undefined && this.highlightDiv) {
32
- const currentTime = this.player.currentTime;
33
- let wordBoundary;
34
- for (const e of this.wordBoundryList) {
35
- if (currentTime * 1000 > e.audioOffset / 10000) {
36
- wordBoundary = e;
37
- } else {
38
- break;
39
- }
40
- }
41
-
42
- if (wordBoundary !== undefined) {
43
- if (~['.', ',', '!', '?'].indexOf(wordBoundary.text)) {
44
- wordBoundary = this.previousWordBoundary ?? undefined;
45
- }
46
-
47
- this.previousWordBoundary = wordBoundary;
48
- this.highlightDiv.innerHTML = this.textToRead.substring(0, wordBoundary.textOffset) +
49
- '<span class=\'co-tts-highlight\'>' + wordBoundary.text + '</span>' +
50
- this.textToRead.substring(wordBoundary.textOffset + wordBoundary.wordLength);
51
- } else {
52
- this.highlightDiv.innerHTML = this.textToRead;
53
- }
54
- }
55
- }, 50);
56
-
57
43
  await this.registerBindings(document);
58
44
  }
59
45
 
60
- async synthesis() {
61
-
62
- }
63
-
64
46
  async registerBindings(node: any) {
65
47
  const nodes = node.childNodes;
66
48
  for (let i = 0; i < nodes.length; i++) {
@@ -95,6 +77,7 @@ export default class TextToSpeech {
95
77
  async handleIdModifier(node: any, attr: Attr) {
96
78
  node.addEventListener('click', async (_: any) => {
97
79
  this.stopPlayer();
80
+ await this.createInterval();
98
81
  this.clickedNode = node;
99
82
  const referenceDiv = document.getElementById(attr.value);
100
83
 
@@ -110,6 +93,7 @@ export default class TextToSpeech {
110
93
 
111
94
  if (referenceDiv.hasAttribute('co-tts.highlight')) {
112
95
  this.highlightDiv = referenceDiv;
96
+ this.originalHighlightDivInnerHTML = referenceDiv.innerHTML;
113
97
  }
114
98
 
115
99
  this.startSynthesizer(node, attr);
@@ -119,6 +103,7 @@ export default class TextToSpeech {
119
103
  async handleAjaxModifier(node: any, attr: Attr) {
120
104
  node.addEventListener('click', async (_: any) => {
121
105
  this.stopPlayer();
106
+ await this.createInterval();
122
107
  this.clickedNode = node;
123
108
  const response = await fetch(attr.value, {
124
109
  method: `GET`,
@@ -133,9 +118,11 @@ export default class TextToSpeech {
133
118
  async handleDefault(node: any, attr: Attr) {
134
119
  node.addEventListener('click', async (_: any) => {
135
120
  this.stopPlayer();
121
+ await this.createInterval();
136
122
  this.clickedNode = node;
137
123
  if (node.hasAttribute('co-tts.highlight')) {
138
124
  this.highlightDiv = node;
125
+ this.originalHighlightDivInnerHTML = node.innerHTML;
139
126
  }
140
127
  if (attr.value === '') {
141
128
  this.textToRead = node.innerHTML;
@@ -147,31 +134,57 @@ export default class TextToSpeech {
147
134
  });
148
135
  }
149
136
 
137
+ async handleWithoutClick(node: any, attr: Attr) {
138
+ this.stopPlayer();
139
+ await this.createInterval();
140
+ this.clickedNode = node;
141
+ if (node.hasAttribute('co-tts.highlight')) {
142
+ this.highlightDiv = node;
143
+ this.originalHighlightDivInnerHTML = node.innerHTML;
144
+ }
145
+ if (attr.value === '') {
146
+ this.textToRead = node.innerHTML;
147
+ } else {
148
+ this.textToRead = attr.value;
149
+ }
150
+
151
+ this.startSynthesizer(node, attr);
152
+ }
153
+
150
154
  async handleStopModifier(node: any, attr: Attr) {
151
155
  node.addEventListener('click', async (_: any) => {
152
156
  await this.stopPlayer();
157
+ document.dispatchEvent(new CustomEvent('COAzureTTSStoppedPlaying', {}));
153
158
  });
154
159
  }
155
160
 
156
161
  async handlePauseModifier(node: any, attr: Attr) {
157
162
  node.addEventListener('click', async (_: any) => {
163
+ await this.clearInterval();
158
164
  await this.player.pause();
165
+ document.dispatchEvent(new CustomEvent('COAzureTTSPausedPlaying', {}));
159
166
  });
160
167
  }
161
168
 
162
169
  async handleResumeModifier(node: any, attr: Attr) {
163
170
  node.addEventListener('click', async (_: any) => {
171
+ await this.createInterval();
164
172
  await this.player.resume();
173
+ document.dispatchEvent(new CustomEvent('COAzureTTSResumedPlaying', {}));
165
174
  });
166
175
  }
167
176
 
168
177
  async stopPlayer() {
178
+ await this.clearInterval();
169
179
  if (this.highlightDiv !== undefined) {
170
- this.highlightDiv.innerHTML = this.textToRead;
180
+ this.highlightDiv.innerHTML = this.originalHighlightDivInnerHTML;
171
181
  }
172
182
 
173
183
  this.textToRead = '';
184
+ this.currentWord = '';
185
+ this.originalHighlightDivInnerHTML = '';
174
186
  this.wordBoundryList = [];
187
+ this.wordEncounters = [];
175
188
  if (this.player !== undefined) {
176
189
  this.player.pause();
177
190
  }
@@ -183,7 +196,7 @@ export default class TextToSpeech {
183
196
  this.speechConfig = SpeechConfig.fromSubscription(this.key, this.region);
184
197
 
185
198
  this.speechConfig.speechSynthesisVoiceName = `Microsoft Server Speech Text to Speech Voice (${this.voice})`;
186
- this.speechConfig.speechSynthesisOutputFormat = 8;
199
+ this.speechConfig.speechSynthesisOutputFormat = SpeechSynthesisOutputFormat.Audio24Khz160KBitRateMonoMp3;
187
200
 
188
201
  this.player = new SpeakerAudioDestination();
189
202
 
@@ -194,17 +207,25 @@ export default class TextToSpeech {
194
207
  this.wordBoundryList.push(e);
195
208
  };
196
209
 
197
- this.player.onAudioEnd = () => {
210
+ this.player.onAudioEnd = async () => {
198
211
  this.stopPlayer();
199
212
 
200
213
  if (this.clickedNode.hasAttribute('co-tts.next')) {
201
214
  const nextNode = document.getElementById(this.clickedNode.getAttribute('co-tts.next'));
202
- if (nextNode) {
215
+ if (nextNode && nextNode.attributes.getNamedItem('co-tts.text')) {
216
+ this.handleWithoutClick(nextNode, nextNode.attributes.getNamedItem('co-tts.text'));
217
+ } else if (nextNode) {
203
218
  nextNode.dispatchEvent(new Event('click'));
204
219
  }
220
+ } else {
221
+ document.dispatchEvent(new CustomEvent('COAzureTTSFinishedPlaying', {}));
205
222
  }
206
223
  };
207
224
 
225
+ this.player.onAudioStart = async () => {
226
+ document.dispatchEvent(new CustomEvent('COAzureTTSStartedPlaying', {}));
227
+ };
228
+
208
229
  this.synthesizer.speakTextAsync(this.textToRead,
209
230
  () => {
210
231
  this.synthesizer.close();
@@ -215,4 +236,62 @@ export default class TextToSpeech {
215
236
  this.synthesizer = undefined;
216
237
  });
217
238
  }
239
+
240
+ async clearInterval() {
241
+ clearInterval(this.interval);
242
+ }
243
+
244
+ async createInterval() {
245
+ this.interval = setInterval(() => {
246
+ if (this.player !== undefined && this.highlightDiv) {
247
+ const currentTime = this.player.currentTime;
248
+ let wordBoundary;
249
+ for (const e of this.wordBoundryList) {
250
+ if (currentTime * 1000 > e.audioOffset / 10000) {
251
+ wordBoundary = e;
252
+ } else {
253
+ break;
254
+ }
255
+ }
256
+
257
+ if (wordBoundary !== undefined) {
258
+ if (~['.', ',', '!', '?'].indexOf(wordBoundary.text)) {
259
+ wordBoundary = this.previousWordBoundary ?? undefined;
260
+ }
261
+
262
+ if (wordBoundary === undefined) {
263
+ this.highlightDiv.innerHTML = this.originalHighlightDivInnerHTML;
264
+ } else {
265
+ if (!this.wordEncounters[wordBoundary.text]) {
266
+ this.wordEncounters[wordBoundary.text] = 0;
267
+ }
268
+
269
+ if (this.currentWord !== wordBoundary.text) {
270
+ this.wordEncounters[wordBoundary.text]++;
271
+ console.log(this.wordEncounters);
272
+ this.currentOffset = this.getPosition(
273
+ this.originalHighlightDivInnerHTML,
274
+ wordBoundary.text,
275
+ this.wordEncounters[wordBoundary.text]
276
+ );
277
+ this.currentWord = wordBoundary.text;
278
+ }
279
+
280
+ this.previousWordBoundary = wordBoundary;
281
+ this.highlightDiv.innerHTML = this.originalHighlightDivInnerHTML.substring(0, this.currentOffset) +
282
+ '<mark class=\'co-tts-highlight\'>' + wordBoundary.text + '</mark>' +
283
+ this.originalHighlightDivInnerHTML.substring(this.currentOffset + wordBoundary.wordLength);
284
+ }
285
+ } else {
286
+ this.highlightDiv.innerHTML = this.originalHighlightDivInnerHTML;
287
+ }
288
+ }
289
+ }, 50);
290
+ }
291
+
292
+ getPosition(string: string, subString: string, index: number) {
293
+ const regex = new RegExp(`\\b${subString}\\b`, 'g');
294
+ console.log(string.split(regex, index).join(subString), regex, index);
295
+ return string.split(regex, index).join(subString).length;
296
+ }
218
297
  }
package/test.xml ADDED
@@ -0,0 +1,9 @@
1
+ <speak version='1.0' xml:lang='nl-NL'>
2
+ <voice xml:lang='nl-NL' name='nl-NL-ColetteNeural'>
3
+ Tijdens deze opdracht
4
+ <lexeme>
5
+ <grapheme>Scotland MV</grapheme>
6
+ <alias>Scotland Media Wave</alias>
7
+ </lexeme>
8
+ </voice>
9
+ </speak>