augnitoambientsdk
Version:
Use this typescript SDK to integrate Augnito’s Ambient Tech within your EMR. To get access credentials or know more about how Augnito Ambient can benefit you, please visit our website and connect with our sales team: https://augnito.ai/
1 lines • 63.5 kB
JavaScript
function e(e,t,i,n){return new(i||(i=Promise))(function(r,o){function s(e){try{u(n.next(e))}catch(e){o(e)}}function a(e){try{u(n.throw(e))}catch(e){o(e)}}function u(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,a)}u((n=n.apply(e,t||[])).next())})}"function"==typeof SuppressedError&&SuppressedError;class t{constructor(e){Object.defineProperty(this,"_config",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"wssBaseURL",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onError",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onMetaEvent",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.wssBaseURL=`wss://${e.server}/ambient/v1/stream-job`}prepareWSSURL(e,t,i,n){let r=this.wssBaseURL;return r+=`?filetype=${e}`,r+=`¬eparams=${t}`,r+=`&subscriptioncode=${this._config.subscriptionCode}`,r+=`&accesskey=${this._config.accessKey}`,r+=`&usertag=${this._config.userTag}`,i&&""!==i&&(r+=`&filename=${i}`),n&&""!==n&&(r+=`&jobid=${n}`),r}}class i{constructor(){}static get Against(){return i.instance||(i.instance=new i),i.instance}NullOrUndefined(e,t){if(null===e)throw new TypeError(`${t} is null`);if(void 0===e)throw new TypeError(`${t} is undefined`);return e}NullOrEmpty(e,t){if(!(e=i.Against.NullOrUndefined(e,t)))throw new TypeError(`${t} is empty`);return e}}var n,r,o,s,a;!function(e){e[e.SPECIALITY=1]="SPECIALITY",e[e.VISIT_TYPE=2]="VISIT_TYPE",e[e.NOTE_TYPE=3]="NOTE_TYPE",e[e.CLINICAL_CODE=4]="CLINICAL_CODE",e[e.LANGUAGE=5]="LANGUAGE",e[e.CDIVersion=7]="CDIVersion"}(n||(n={})),function(e){e[e.SoapNote=1]="SoapNote",e[e.PatientNote=2]="PatientNote",e[e.ReferralNote=3]="ReferralNote",e[e.ConsultationSummary=4]="ConsultationSummary",e[e.CDISuggestions=102]="CDISuggestions"}(r||(r={})),function(e){e.AUTH01="AUTH01",e.AUTH02="AUTH02",e.WSAUTH01="WSAUTH01",e.WSAUTH02="WSAUTH02",e.WSAUTH03="WSAUTH03",e.WSAUTH04="WSAUTH04",e.WSJOB01="WSJOB01",e.WSJOB02="WSJOB02",e.WSJOB03="WSJOB03",e.WSJOB04="WSJOB04",e.WSJOB05="WSJOB05",e.WSACC01="WSACC01",e.WSAUD01="WSAUD01",e.SDK01="SDK01",e.SDK02="SDK02",e.SDK03="SDK03",e.SDK04="SDK04",e.SDK05="SDK05",e.SDK06="SDK06",e.SDK07="SDK07",e.SDK08="SDK08",e.SDK12="SDK12",e.SDK13="SDK13",e.SDK14="SDK14",e.ERRUNKNOWN="ERRUNKNOWN"}(o||(o={}));class u extends Error{constructor(e,t){super(e),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.code=t,this.name="HttpCodedError",Object.setPrototypeOf(this,u.prototype)}}!function(e){e.Detailed="Detailed",e.Concise="Concise"}(s||(s={})),function(e){e.DashFormat="Dash-format",e.Paragraph="Paragraph"}(a||(a={}));class c{makePostRequest(t,i){return e(this,void 0,void 0,function*(){try{const n=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(!n.ok){const t=yield n.text();var e=JSON.parse(t);throw new u(e.message,e.code.toString())}return yield n.json()}catch(e){throw e}})}makePatchRequest(t,i){return e(this,void 0,void 0,function*(){try{const n=yield fetch(t,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(!n.ok){const t=yield n.text();var e=JSON.parse(t);throw new u(e.message,n.status.toString())}return yield n.json()}catch(e){throw e instanceof u?e:new u("500",e.message||"Unexpected error")}})}}class l extends c{constructor(e){super(),Object.defineProperty(this,"_config",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"_baseUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._baseUrl=`https://${e.server}/ambient/v1`}getURL(e){return`${this._baseUrl}${e}`}GetNoteParams(){return e(this,void 0,void 0,function*(){const e=this.getURL("/note-params"),t={SubscriptionCode:this._config.subscriptionCode,AccessKey:this._config.accessKey,UserTag:this._config.userTag};return yield this.makePostRequest(e,t)})}ListJobs(t,n){return e(this,void 0,void 0,function*(){i.Against.NullOrEmpty(t,"Page Size");const e=this.getURL("/list-jobs"),r={SubscriptionCode:this._config.subscriptionCode,AccessKey:this._config.accessKey,UserTag:this._config.userTag,PageSize:t,PageID:n};return yield this.makePostRequest(e,r)})}FetchJob(t){return e(this,void 0,void 0,function*(){i.Against.NullOrEmpty(t,"Job Id");const e=this.getURL("/fetch-job"),n={SubscriptionCode:this._config.subscriptionCode,AccessKey:this._config.accessKey,UserTag:this._config.userTag,JobID:t};return yield this.makePostRequest(e,n)})}SendFinalNote(t,n){return e(this,void 0,void 0,function*(){i.Against.NullOrEmpty(t,"Job Id"),i.Against.NullOrEmpty(n,"Note Data");const e=this.getURL("/send-final-note"),r={SubscriptionCode:this._config.subscriptionCode,AccessKey:this._config.accessKey,UserTag:this._config.userTag,JobID:t,SoapData:n};return yield this.makePostRequest(e,r)})}DeleteNotes(t){return e(this,void 0,void 0,function*(){i.Against.NullOrEmpty(t,"Job Id");const e=this.getURL("/delete-job"),n={SubscriptionCode:this._config.subscriptionCode,AccessKey:this._config.accessKey,UserTag:this._config.userTag,JobIDs:t};return yield this.makePostRequest(e,n)})}RenameNoteTitle(t,n){return e(this,void 0,void 0,function*(){i.Against.NullOrEmpty(t,"Job Id"),i.Against.NullOrEmpty(n,"Job Name");const e=this.getURL("/rename-job"),r={SubscriptionCode:this._config.subscriptionCode,AccessKey:this._config.accessKey,UserTag:this._config.userTag,JobID:t,JobName:n};return yield this.makePostRequest(e,r)})}DownloadNotePDF(t,n,r,o,s,a){return e(this,void 0,void 0,function*(){i.Against.NullOrEmpty(t,"Job Id");const e=this.getURL("/download-pdf");var u=s;u&&""!=u||(u='{"PatientName":"","PatientID":"","Age":"","Gender":"","ReceivingDoctor":"","DoctorName":"","DoctorDesignation":"","DoctorEmail":""}');const c={SubscriptionCode:this._config.subscriptionCode,AccessKey:this._config.accessKey,UserTag:this._config.userTag,JobID:t,NoteType:n,Language:null!=o?o:"English",SpecialityID:r,Regenerate:null!=a&&a,PersonnelInfo:u};return yield this.makePostRequest(e,c)})}EndJob(t){return e(this,void 0,void 0,function*(){i.Against.NullOrEmpty(t,"Job Id");const e=this.getURL("/end-job"),n={SubscriptionCode:this._config.subscriptionCode,AccessKey:this._config.accessKey,UserTag:this._config.userTag,JobID:t};return yield this.makePostRequest(e,n)})}UpdatePatientContext(t,n,r){return e(this,void 0,void 0,function*(){i.Against.NullOrEmpty(t,"Job Id"),i.Against.NullOrEmpty(n,"Patient Context");const e=this.getURL("/patient-context"),o={SubscriptionCode:this._config.subscriptionCode,AccessKey:this._config.accessKey,UserTag:this._config.userTag,JobID:t,NewContext:n,Replace:r};return yield this.makePostRequest(e,o)})}GenerateSuggestions(t,n,r,o,s,a){return e(this,void 0,void 0,function*(){i.Against.NullOrEmpty(t,"Job Id");var e=this.getURL("/cdi");a&&2===a&&(e=this.getURL("/cdi").replace("/v1","/v2"));const u={SubscriptionCode:this._config.subscriptionCode,AccessKey:this._config.accessKey,UserTag:this._config.userTag,JobID:t,Regenerate:n,SoapData:r,PatientContext:o,Codes:s};return yield this.makePostRequest(e,u)})}ModifyGeneratedNote(t,n,r){return e(this,void 0,void 0,function*(){i.Against.NullOrEmpty(t,"Job Id");const e=this.getURL("/modify-note"),o={SubscriptionCode:this._config.subscriptionCode,AccessKey:this._config.accessKey,UserTag:this._config.userTag,JobID:t,NoteType:n,NewNote:null!=r?r:""};return yield this.makePostRequest(e,o)})}FetchTranscription(t){return e(this,void 0,void 0,function*(){i.Against.NullOrEmpty(t,"Job Id");const e=this.getURL("/fetch-transcript"),n={SubscriptionCode:this._config.subscriptionCode,AccessKey:this._config.accessKey,UserTag:this._config.userTag,JobID:t};return yield this.makePostRequest(e,n)})}SendFeedback(t,n,r,o){return e(this,void 0,void 0,function*(){i.Against.NullOrEmpty(t,"Job Id"),i.Against.NullOrUndefined(n,"Rating");const e=this.getURL("/feedback").replace("/v1","/v2"),s={SubscriptionCode:this._config.subscriptionCode,AccessKey:this._config.accessKey,UserTag:this._config.userTag,JobID:t,Rating:n,FeedBack:null!=r?r:"",Type:null!=o?o:""};return yield this.makePostRequest(e,s)})}}class h{static log(e,t){const i=null!=t?t:this.defaultTag;console.log(`${i}:`,e)}static error(e,t){const i=null!=t?t:this.defaultTag;console.error(`${i}:`,e)}}function d(){d=function(){return t};var e,t={},i=Object.prototype,n=i.hasOwnProperty,r=Object.defineProperty||function(e,t,i){e[t]=i.value},o="function"==typeof Symbol?Symbol:{},s=o.iterator||"@@iterator",a=o.asyncIterator||"@@asyncIterator",u=o.toStringTag||"@@toStringTag";function c(e,t,i){return Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{c({},"")}catch(e){c=function(e,t,i){return e[t]=i}}function l(e,t,i,n){var o=t&&t.prototype instanceof S?t:S,s=Object.create(o.prototype),a=new O(n||[]);return r(s,"_invoke",{value:P(e,i,a)}),s}function h(e,t,i){try{return{type:"normal",arg:e.call(t,i)}}catch(e){return{type:"throw",arg:e}}}t.wrap=l;var f="suspendedStart",g="suspendedYield",p="executing",v="completed",b={};function S(){}function m(){}function y(){}var C={};c(C,s,function(){return this});var E=Object.getPrototypeOf,k=E&&E(E(_([])));k&&k!==i&&n.call(k,s)&&(C=k);var I=y.prototype=S.prototype=Object.create(C);function A(e){["next","throw","return"].forEach(function(t){c(e,t,function(e){return this._invoke(t,e)})})}function R(e,t){function i(r,o,s,a){var u=h(e[r],e,o);if("throw"!==u.type){var c=u.arg,l=c.value;return l&&"object"==typeof l&&n.call(l,"__await")?t.resolve(l.__await).then(function(e){i("next",e,s,a)},function(e){i("throw",e,s,a)}):t.resolve(l).then(function(e){c.value=e,s(c)},function(e){return i("throw",e,s,a)})}a(u.arg)}var o;r(this,"_invoke",{value:function(e,n){function r(){return new t(function(t,r){i(e,n,t,r)})}return o=o?o.then(r,r):r()}})}function P(t,i,n){var r=f;return function(o,s){if(r===p)throw Error("Generator is already running");if(r===v){if("throw"===o)throw s;return{value:e,done:!0}}for(n.method=o,n.arg=s;;){var a=n.delegate;if(a){var u=w(a,n);if(u){if(u===b)continue;return u}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if(r===f)throw r=v,n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);r=p;var c=h(t,i,n);if("normal"===c.type){if(r=n.done?v:g,c.arg===b)continue;return{value:c.arg,done:n.done}}"throw"===c.type&&(r=v,n.method="throw",n.arg=c.arg)}}}function w(t,i){var n=i.method,r=t.iterator[n];if(r===e)return i.delegate=null,"throw"===n&&t.iterator.return&&(i.method="return",i.arg=e,w(t,i),"throw"===i.method)||"return"!==n&&(i.method="throw",i.arg=new TypeError("The iterator does not provide a '"+n+"' method")),b;var o=h(r,t.iterator,i.arg);if("throw"===o.type)return i.method="throw",i.arg=o.arg,i.delegate=null,b;var s=o.arg;return s?s.done?(i[t.resultName]=s.value,i.next=t.nextLoc,"return"!==i.method&&(i.method="next",i.arg=e),i.delegate=null,b):s:(i.method="throw",i.arg=new TypeError("iterator result is not an object"),i.delegate=null,b)}function T(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function D(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function O(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(T,this),this.reset(!0)}function _(t){if(t||""===t){var i=t[s];if(i)return i.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var r=-1,o=function i(){for(;++r<t.length;)if(n.call(t,r))return i.value=t[r],i.done=!1,i;return i.value=e,i.done=!0,i};return o.next=o}}throw new TypeError(typeof t+" is not iterable")}return m.prototype=y,r(I,"constructor",{value:y,configurable:!0}),r(y,"constructor",{value:m,configurable:!0}),m.displayName=c(y,u,"GeneratorFunction"),t.isGeneratorFunction=function(e){var t="function"==typeof e&&e.constructor;return!!t&&(t===m||"GeneratorFunction"===(t.displayName||t.name))},t.mark=function(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,y):(e.__proto__=y,c(e,u,"GeneratorFunction")),e.prototype=Object.create(I),e},t.awrap=function(e){return{__await:e}},A(R.prototype),c(R.prototype,a,function(){return this}),t.AsyncIterator=R,t.async=function(e,i,n,r,o){void 0===o&&(o=Promise);var s=new R(l(e,i,n,r),o);return t.isGeneratorFunction(i)?s:s.next().then(function(e){return e.done?e.value:s.next()})},A(I),c(I,u,"Generator"),c(I,s,function(){return this}),c(I,"toString",function(){return"[object Generator]"}),t.keys=function(e){var t=Object(e),i=[];for(var n in t)i.push(n);return i.reverse(),function e(){for(;i.length;){var n=i.pop();if(n in t)return e.value=n,e.done=!1,e}return e.done=!0,e}},t.values=_,O.prototype={constructor:O,reset:function(t){if(this.prev=0,this.next=0,this.sent=this._sent=e,this.done=!1,this.delegate=null,this.method="next",this.arg=e,this.tryEntries.forEach(D),!t)for(var i in this)"t"===i.charAt(0)&&n.call(this,i)&&!isNaN(+i.slice(1))&&(this[i]=e)},stop:function(){this.done=!0;var e=this.tryEntries[0].completion;if("throw"===e.type)throw e.arg;return this.rval},dispatchException:function(t){if(this.done)throw t;var i=this;function r(n,r){return a.type="throw",a.arg=t,i.next=n,r&&(i.method="next",i.arg=e),!!r}for(var o=this.tryEntries.length-1;o>=0;--o){var s=this.tryEntries[o],a=s.completion;if("root"===s.tryLoc)return r("end");if(s.tryLoc<=this.prev){var u=n.call(s,"catchLoc"),c=n.call(s,"finallyLoc");if(u&&c){if(this.prev<s.catchLoc)return r(s.catchLoc,!0);if(this.prev<s.finallyLoc)return r(s.finallyLoc)}else if(u){if(this.prev<s.catchLoc)return r(s.catchLoc,!0)}else{if(!c)throw Error("try statement without catch or finally");if(this.prev<s.finallyLoc)return r(s.finallyLoc)}}}},abrupt:function(e,t){for(var i=this.tryEntries.length-1;i>=0;--i){var r=this.tryEntries[i];if(r.tryLoc<=this.prev&&n.call(r,"finallyLoc")&&this.prev<r.finallyLoc){var o=r;break}}o&&("break"===e||"continue"===e)&&o.tryLoc<=t&&t<=o.finallyLoc&&(o=null);var s=o?o.completion:{};return s.type=e,s.arg=t,o?(this.method="next",this.next=o.finallyLoc,b):this.complete(s)},complete:function(e,t){if("throw"===e.type)throw e.arg;return"break"===e.type||"continue"===e.type?this.next=e.arg:"return"===e.type?(this.rval=this.arg=e.arg,this.method="return",this.next="end"):"normal"===e.type&&t&&(this.next=t),b},finish:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var i=this.tryEntries[t];if(i.finallyLoc===e)return this.complete(i.completion,i.afterLoc),D(i),b}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var i=this.tryEntries[t];if(i.tryLoc===e){var n=i.completion;if("throw"===n.type){var r=n.arg;D(i)}return r}}throw Error("illegal catch attempt")},delegateYield:function(t,i,n){return this.delegate={iterator:_(t),resultName:i,nextLoc:n},"next"===this.method&&(this.arg=e),b}},t}function f(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var i=e[Symbol.toPrimitive];if(void 0!==i){var n=i.call(e,t||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}function g(e,t,i,n,r,o,s){try{var a=e[o](s),u=a.value}catch(e){return void i(e)}a.done?t(u):Promise.resolve(u).then(n,r)}function p(e){return function(){var t=this,i=arguments;return new Promise(function(n,r){var o=e.apply(t,i);function s(e){g(o,n,r,s,a,"next",e)}function a(e){g(o,n,r,s,a,"throw",e)}s(void 0)})}}function v(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function b(e,t){for(var i=0;i<t.length;i++){var n=t[i];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,f(n.key),n)}}function S(e,t,i){return t&&b(e.prototype,t),i&&b(e,i),Object.defineProperty(e,"prototype",{writable:!1}),e}Object.defineProperty(h,"defaultTag",{enumerable:!0,configurable:!0,writable:!0,value:"AugnitoAmbientSDK"});var m="DONE",y="PAUSESOCKET",C="RESUMESOCKET",E="INTENT_START_STREAM",k="CLOSE",I=S(function e(t,i,n,r,o,s,a,u,c,l,h,d,f){v(this,e),this.worker,this.onFinalResultCallback=o,this.onErrorCallback=a,this.onPartialResultCallback=s,this.onSessionEventCallback=u,this.onOtherResultsCallback=c,this.onSpeechResponseCallback=l,this.onJobStatusCallback=h,this.packetSeqId=0,this.audioDuration=0,this.shouldSendAudioDataSequence=r,this.heavyOp,this.idleLoop,this.lastSent,this.enableLogs=t,this.eosMessage=i||"EOS",this.socketTimeoutInterval=n||1e4,this.bufferSizeInterval=d,this.switchToRegularSpeech=f},[{key:"Start",value:function(e,t,i){var n=this;this.audioDuration=e;var r="\n (() => {\n (".concat(A.toString(),")(").concat(JSON.stringify(m),", ").concat(JSON.stringify(this.eosMessage),", ").concat(JSON.stringify(k),", ").concat(JSON.stringify(1e4),", ").concat(JSON.stringify(this.socketTimeoutInterval),", ").concat(JSON.stringify(12e4),", ").concat(JSON.stringify(1e3),", ").concat(JSON.stringify(100),", ").concat(JSON.stringify(1e4),", ").concat(JSON.stringify(t),", ").concat(JSON.stringify(this.enableLogs),", ").concat(JSON.stringify(this.shouldSendAudioDataSequence),",").concat(JSON.stringify(y),", ").concat(JSON.stringify(C),", ").concat(JSON.stringify(E),", ").concat(JSON.stringify(this.switchToRegularSpeech),", ").concat(JSON.stringify(i),", ").concat(JSON.stringify(this.heavyOp),");\n })();\n");this.worker=new Worker(URL.createObjectURL(new Blob([r],{type:"application/javascript"}))),this.worker.onmessage=function(e){n.enableLogs&&console.log("Augnito [MAIN]: "+JSON.stringify(e.data));var t=e.data;"final"==t.type?n.onFinalResultCallback(t.data):"partial"==t.type?n.onPartialResultCallback(t.data):"meta"==t.type?n.onSessionEventCallback(t.data):"error"==t.type?n.onErrorCallback(t.data):"other"==t.type?n.onOtherResultsCallback(t.data):"jobstatus"==t.type?n.onJobStatusCallback(t.data.status):"speechResponse"==t.type&&n.onSpeechResponseCallback(t.data)}}},{key:"createAudioPacketHeader",value:function(e){this.audioDuration>0&&(this.packetSeqId=Math.ceil(this.audioDuration/this.bufferSizeInterval)+2,this.audioDuration=0),this.packetSeqId++;for(var t=new ArrayBuffer(16),i=new DataView(t),n=0;n<4;n++)i.setUint8(n,"@BSR".charCodeAt(n));return i.setBigInt64(4,BigInt(this.packetSeqId),!1),i.setUint8(12,e?1:0),t}},{key:"appendAudioData",value:function(e,t){var i=e.byteLength+t.byteLength,n=new ArrayBuffer(i),r=new Uint8Array(n);return r.set(new Uint8Array(e),0),r.set(new Uint8Array(t),e.byteLength),n}},{key:"Send",value:function(e){var t;if(this.lastSent=+new Date,e===k)null===(t=this.worker)||void 0===t||t.postMessage(k);else if(e===m)if(this.shouldSendAudioDataSequence){var i,n=this.createAudioPacketHeader(!0);null===(i=this.worker)||void 0===i||i.postMessage(n)}else{var r;null===(r=this.worker)||void 0===r||r.postMessage(m)}else if(e==y){var o;null===(o=this.worker)||void 0===o||o.postMessage(y)}else if(e==C){var s;null===(s=this.worker)||void 0===s||s.postMessage(C)}else if(e==E){var a;null===(a=this.worker)||void 0===a||a.postMessage(E)}else if(e===this.eosMessage){var u;this.shouldSendAudioDataSequence||null===(u=this.worker)||void 0===u||u.postMessage(e)}else{var c,l=[];this.shouldSendAudioDataSequence?(n=this.createAudioPacketHeader(!1),l=this.appendAudioData(n,e)):l=e,void 0!==l&&(null===(c=this.worker)||void 0===c||c.postMessage(l,[l]))}}},{key:"HeavyOp",set:function(e){this.heavyOp=e}}]);function A(e,t,i,n,r,o,s,a,u,c,l,h,d,f,g,p,v,b){var S,m,y,C,E,k,I,A,R,P=[],w=[],T=!1,D=[],O=!1,_=!1,N=!1,U="",x=v;function L(){S=+new Date,(k=""!=U?new WebSocket(c+"&jobid="+U):new WebSocket(c)).onopen=function(e){l&&console.log("Augnito: WebSocket connection established - "+JSON.stringify(e)),D.length>0&&(_=!0)},k.onmessage=function(e){l&&console.log("Augnito: Message from server - "+JSON.stringify(e.data)),y=+new Date,function(e){try{if("PING"===e.data)C=+new Date,self.postMessage({type:"ping",data:e.data});else{var t=JSON.parse(e.data);if(l&&console.log("Augnito [WORKER]: "+JSON.stringify(t)),"meta"==t.Type){t.JobID&&(U=t.JobID,console.log("Augnito JobID:",U)),self.postMessage({type:"meta",data:e.data});var i=JSON.parse(e.data);N=!(!i.Event||"INVALID_AUTH_CREDENTIALS"!==i.Event.Type)}else if(t.Result&&t.Result.Final){var n=JSON.stringify(t.Result);b&&(n=b(JSON.stringify(t.Result)),console.log(n)),self.postMessage({type:"final",data:n})}else t.Result&&!t.Result.Final?self.postMessage({type:"partial",data:t.Result.Transcript}):"ACK"==t.Type?(D=D.filter(function(e){return e.packetNumber>t.Index}),self.postMessage({type:"other",data:e.data})):"ERROR"==t.Type?("Timeout exceeded"==t.Data&&(O=!0,K()),self.postMessage({type:"error",data:e.data})):"STATUS"==t.Type?self.postMessage({type:"jobstatus",data:{status:e.data}}):self.postMessage({type:"speechResponse",data:e.data})}}catch(e){self.postMessage({type:"error",data:"invalid response"})}}(e)},k.onerror=function(e){console.error("WebSocket error: ",e),self.postMessage({type:"error",data:JSON.stringify(e)})},k.onclose=function(e){l&&console.log("Augnito: WebSocket connection closed - "+JSON.stringify(e)),K()},m=+new Date,y=m,C=+new Date}function M(e){if(k&&k.readyState===WebSocket.OPEN){k.send(e);var i=+new Date;return m<=y&&(y=i-1),m=i,!0}return e===t?(l&&console.warn("Gulping ".concat(t," as socket seems already closed...")),K(),!0):(+new Date-S>n&&!N&&L(),!1)}function J(e){P.push(e)}function K(){O&&(clearInterval(I),clearInterval(A),clearInterval(R),P=[],D=[],self.close())}L(),I=setInterval(function(){if(_){for(var e=0;e<D.length;e++){if(!M(D[e].packetData))break}_=!1}else for(;P.length>0;){var t=P.shift();if(!M(t)){P.unshift(t);break}if(h){var i=new DataView(t),n={packetNumber:Number(i.getBigInt64(4)),packetData:t};D.push(n)}}},a),A=setInterval(function(){if(k&&k.readyState===WebSocket.OPEN){var e=+new Date;(p?m>y&&e-y>r:e-C>r)&&(l&&console.error("No data received since more than ".concat(r/1e3," secs, closing time...")),k.close())}},s),R=setInterval(function(){if(k&&k.readyState===WebSocket.OPEN){var e=+new Date;m&&e-m>o&&(l&&console.warn("No data sent since more than ".concat(o/1e3," secs, closing time...")),k.close())}},u),self.onmessage=function(n){if(n.data===i)U="",O=!0,N=!0,k.close();else if(n.data===e)J(t),U="",l&&console.log("Augnito: Worker received DONE, time to terminate..."),O=!0;else if(n.data===d)x=!0;else if(n.data===g)T=!0;else if(n.data===f){if(J(E),w.length>0)for(var r=0;r<w.length;r++)J(w[r]);w=[],T=!1,x=!1,E=[]}else x&&!T?E=n.data:x&&T?w.push(n.data):J(n.data)}}var R,P,w,T,D,O,_,N,U,x=S(function e(t,i,n,r,o,s,a,u,c,l,h,d,f,g,p,b,S,m,y,C,E,k,A,R,P){v(this,e),this.audioContext,this.audioStream,this.executor=new I(i,s,a,u,S,m,y,E,k,A,P,r,d),this.executor.HeavyOp=b,this.source,this.processorNode,this.isPaused=!1,this.isStreaming=!1,this.audioData=[],this.isDebug=n,this.enableLogs=i,this.onStateChanged=C,this.onIntensity=R,this.onError=y,this.bufferSizeInterval=r,this.pausedBufferInterval=null!=o?o:1,this.shouldReadIntensity=h,this.closeSocketWithoutEOS=!1,this.shouldPreIntialiseRecorder=null!=l&&l,this.echoCancellation=f,this.noiseSuppression=g,this.autoGainControl=p,this.shouldPreIntialiseRecorder&&this.InitialiseMediaStream(c,t)},[{key:"InitialiseMediaStream",value:(U=p(d().mark(function e(t,i){return d().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.createMediaStreamSourceNode();case 2:if(this.source){e.next=5;break}return console.error("Error: unable to create source node"),e.abrupt("return",!1);case 5:return e.next=7,this.createProcessorNode();case 7:if(this.processorNode){e.next=10;break}return console.error("Error: unable to create processor node"),e.abrupt("return",!1);case 10:this.source.connect(this.processorNode).connect(this.audioContext.destination),this.log("AudioContext Sample Rate: "+this.audioContext.sampleRate),""!==i&&this.executor.Start(t,i,this.shouldPreIntialiseRecorder);case 13:case"end":return e.stop()}},e,this)})),function(e,t){return U.apply(this,arguments)})},{key:"StartStream",value:(N=p(d().mark(function e(t,i){return d().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(this.log("New stream started..."),this.shouldPreIntialiseRecorder&&this.source){e.next=6;break}return e.next=4,this.InitialiseMediaStream(t,i,!1);case 4:e.next=7;break;case 6:this.shouldPreIntialiseRecorder&&this.executor.Send(C);case 7:if(!this.IsMicrophoneMuted){e.next=13;break}if(!this.audioContext||"running"!=this.audioContext.state){e.next=11;break}return e.next=11,this.audioContext.suspend();case 11:return this.onError(JSON.stringify({Type:"ERROR",Data:"Microphone is muted."})),e.abrupt("return",!1);case 13:return this.onStateChanged(!0),this.isStreaming=!0,e.abrupt("return",!0);case 16:case"end":return e.stop()}},e,this)})),function(e,t){return N.apply(this,arguments)})},{key:"createBufferedSourceNode",value:(_=p(d().mark(function e(){var t;return d().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.loadAudio();case 2:if(t=e.sent){e.next=6;break}return console.error("Error: unable to create audio buffer"),e.abrupt("return");case 6:this.source=this.audioContext.createBufferSource(),this.source.buffer=t,this.source.loop=!0,this.source.start();case 10:case"end":return e.stop()}},e,this)})),function(){return _.apply(this,arguments)})},{key:"createMediaStreamSourceNode",value:(O=p(d().mark(function e(){var t,i,n=this;return d().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.prev=0,t={channelCount:1,noiseSuppression:void 0!==this.noiseSuppression&&this.noiseSuppression},void 0!==this.echoCancellation&&(t.echoCancellation=this.echoCancellation,t.googEchoCancellation=this.echoCancellation),void 0!==this.noiseSuppression&&(t.googNoiseSuppression=this.noiseSuppression),void 0!==this.autoGainControl&&(t.autoGainControl=this.autoGainControl,t.googAutoGainControl=this.autoGainControl),e.next=7,navigator.mediaDevices.getUserMedia({audio:t});case 7:this.audioStream=e.sent,this.audioContext=new AudioContext,this.source=this.audioContext.createMediaStreamSource(this.audioStream),this.audioStream.getAudioTracks()[0].addEventListener("ended",function(){n.onError(JSON.stringify({Type:"ERROR",Data:"Audio track ended. Possibly the mic was unplugged."}))}),e.next=18;break;case 13:e.prev=13,e.t0=e.catch(0),i="","NotAllowedError"==e.t0.name?i="Mic permission denied":"NotFoundError"===e.t0.name&&(i="No suitable media device found"),this.onError(JSON.stringify({Type:"ERROR",Data:i}));case 18:case"end":return e.stop()}},e,this,[[0,13]])})),function(){return O.apply(this,arguments)})},{key:"loadAudio",value:(D=p(d().mark(function e(){var t,i,n;return d().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.prev=0,e.next=3,fetch("./radiology_speed_test.wav");case 3:return t=e.sent,e.next=6,t.arrayBuffer();case 6:return i=e.sent,e.next=9,this.audioContext.decodeAudioData(i);case 9:return n=e.sent,e.abrupt("return",n);case 13:return e.prev=13,e.t0=e.catch(0),console.error("Unable to fetch the audio file. Error: ".concat(e.t0.message)),e.abrupt("return",null);case 17:case"end":return e.stop()}},e,this,[[0,13]])})),function(){return D.apply(this,arguments)})},{key:"createProcessorNode",value:(T=p(d().mark(function e(){var t,i=this;return d().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.prev=0,e.next=3,this.audioContext.audioWorklet.addModule("data:application/javascript,".concat(encodeURIComponent('class MyAudioWorkletProcessor extends AudioWorkletProcessor {\n constructor() {\n super();\n this.accumulator = [];\n this.pauseSocketStreaming = false;\n this.sampleVal = 0;\n this.sampleSize = 0;\n this.intensityFrameCount = 0;\n this.reset();\n this.isProcessing = true;\n // message received from main-thread\n this.port.onmessage = (e) => {\n console.log("Augnito: Worklet received event - ", e.data);\n if (this.sampleSize > 0) {\n this.accumulator.push(this.sampleVal / this.sampleSize);\n }\n \n if (e.data == "PAUSE" || e.data == "STOP" || e.data == "PAUSESOCKET") {\n // append silence to get last word ASR.\n const silenceSize = 16000 * 2;\n for (let i = 0; i < silenceSize; i++) {\n this.accumulator.push(0);\n }\n }\n this.send();\n this.reset();\n if (e.data == "STOP") {\n // message sent to main-thread\n this.port.postMessage({type:"DONE", value:"DONE"});\n this.isProcessing = false;\n \n }\n if(e.data == "PAUSESOCKET"){\n this.pauseSocketStreaming = true;\n this.port.postMessage("PAUSESOCKET");\n } else if(e.data == "RESUMESOCKET"){\n this.pauseSocketStreaming = false;\n } \n };\n }\n\n static get parameterDescriptors() {\n return [\n {\n name: "sampleRate",\n defaultValue: 16000,\n minValue: 16000,\n maxValue: 6 * 16000,\n },\n {\n name: "bufferSizeInterval",\n defaultValue: 1,\n minValue: 1,\n maxValue: 100,\n },\n {\n name: "pausedBufferInterval",\n defaultValue: 1,\n minValue: 0,\n maxValue: 100,\n },\n {\n name: "shouldReadIntensity",\n defaultValue: false,\n minValue: 0,\n maxValue: 1,\n },\n ];\n }\n\n // 128 frames\n process(inputList, outputList, params) {\n const input = inputList[0];\n if (input && input.length && input[0].length) {\n const channelData = input[0];\n const output = outputList[0];\n const inputSampleRate = params.sampleRate[0];\n const sampleRatio = inputSampleRate / 16000\n const bufferSizeInterval = params["bufferSizeInterval"][0];\n const pausedBufferInterval = params["pausedBufferInterval"][0];\n const shouldReadIntensity = params["shouldReadIntensity"][0];\n\n let sumSquares = 0; // For intensity\n let sampleCount = 0;\n\n // console.log("BufferSizeInterval", bufferSizeInterval);\n // Jackpot\n input[0].forEach((float32Element, index) => {\n const int16Element = Math.min(1, Math.max(-1, float32Element)) * 0x7fff;\n this.sampleVal += int16Element;\n this.sampleSize += 1;\n // Accumulate for intensity (RMS)\n sumSquares += float32Element * float32Element;\n sampleCount++;\n \n\n if (this.sampleSize >= sampleRatio) {\n const fraction = this.sampleSize - sampleRatio \n this.sampleVal -= fraction * int16Element;\n\n this.accumulator.push(this.sampleVal / sampleRatio);\n \n this.sampleVal = fraction * int16Element;\n this.sampleSize = fraction;\n }\n\n // Comment this when streaming microphone audio\n // output[0][index] = float32Element;\n });\n if(this.pauseSocketStreaming){\n if (this.accumulator.length >= 125 * 128 * pausedBufferInterval) {\n this.send();\n }\n } else{\n if (this.accumulator.length >= 125 * 128 * bufferSizeInterval) {\n this.send();\n }\n }\n if(shouldReadIntensity){\n \n // Throttled intensity post\n this.intensityFrameCount = (this.intensityFrameCount || 0) + 1;\n if (this.intensityFrameCount >= 15 && sampleCount > 0) {\n const rms = Math.sqrt(sumSquares / sampleCount);\n const normalized = Math.min(1, rms); // [0–1] scale\n this.port.postMessage({ type: \'intensity\', value: normalized });\n this.intensityFrameCount = 0;\n }\n }\n }\n return this.isProcessing;\n }\n\n send() {\n if (this.accumulator.length == 0) return;\n const audioData = new Int16Array(this.accumulator);\n // message sent to main-thread - transferrable\n this.port.postMessage({ type: \'audioData\', value: audioData.buffer }, [audioData.buffer]);\n this.accumulator = [];\n }\n\n reset() {\n this.sampleVal = 0;\n this.sampleSize = 0;\n }\n}\n\nregisterProcessor("worklet-processor", MyAudioWorkletProcessor);')));case 3:this.processorNode=new AudioWorkletNode(this.audioContext,"worklet-processor"),this.processorNode.parameters.get("sampleRate").setValueAtTime(this.audioContext.sampleRate,this.audioContext.currentTime),this.processorNode.parameters.get("bufferSizeInterval").setValueAtTime(this.bufferSizeInterval,this.audioContext.currentTime),this.processorNode.parameters.get("pausedBufferInterval").setValueAtTime(this.pausedBufferInterval,this.audioContext.currentTime),this.processorNode.parameters.get("shouldReadIntensity").setValueAtTime(null!==(t=this.shouldReadIntensity)&&void 0!==t&&t,this.audioContext.currentTime),this.processorNode.port.onmessage=function(e){var t=e.data,n=t.type,r=t.value;if(n==m)i.log("Worklet processing done, clearing resources..."),i.isDebug&&i.saveAudio(),i.cleanup();else if(e.data==y)i.executor.Send(y);else{var o;"intensity"===n?null===(o=i.onIntensity)||void 0===o||o.call(i,r):"audioData"===n&&i.isDebug&&new Int16Array(r).forEach(function(e){i.audioData.length<=288e5&&i.audioData.push(e)})}i.executor&&(i.closeSocketWithoutEOS?(i.executor.Send(k),i.closeSocketWithoutEOS=!1):"intensity"!==n&&i.executor.Send(r))},e.next=18;break;case 15:e.prev=15,e.t0=e.catch(0),console.error("Error: Unable to create worklet node: ",e.t0);case 18:case"end":return e.stop()}},e,this,[[0,15]])})),function(){return T.apply(this,arguments)})},{key:"PauseStream",value:(w=p(d().mark(function e(){return d().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if("running"!=this.audioContext.state){e.next=9;break}if(this.shouldPreIntialiseRecorder){e.next=8;break}return e.next=4,this.audioContext.suspend();case 4:this.log("Stream paused..."),this.processorNode.port.postMessage("PAUSE"),e.next=9;break;case 8:this.processorNode.port.postMessage(y);case 9:this.onStateChanged(!1),this.isPaused=!0,this.isStreaming=!1;case 12:case"end":return e.stop()}},e,this)})),function(){return w.apply(this,arguments)})},{key:"ResumeStream",value:(P=p(d().mark(function e(){return d().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(this.shouldPreIntialiseRecorder||"suspended"!=this.audioContext.state){e.next=9;break}if(!this.IsMicrophoneMuted){e.next=4;break}return this.onError(JSON.stringify({Type:"ERROR",Data:"Microphone is muted."})),e.abrupt("return");case 4:return e.next=6,this.audioContext.resume();case 6:this.log("Stream resumed..."),e.next=11;break;case 9:this.processorNode.port.postMessage(C),this.executor.Send(C);case 11:this.onStateChanged(!0),this.isPaused=!1,this.isStreaming=!0;case 14:case"end":return e.stop()}},e,this)})),function(){return P.apply(this,arguments)})},{key:"IsPaused",get:function(){return this.isPaused}},{key:"IsStreaming",get:function(){return this.isStreaming}},{key:"IsMicrophoneMuted",get:function(){return this.audioStream.getAudioTracks()[0].muted}},{key:"StopStream",value:(R=p(d().mark(function e(t){var i,n,r,o;return d().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if("suspended"===(null===(i=this.audioContext)||void 0===i?void 0:i.state)){e.next=4;break}return e.next=3,null===(o=this.audioContext)||void 0===o?void 0:o.suspend();case 3:this.onStateChanged(!1);case 4:this.log("Stream stopped..."),this.isStreaming=!1,this.closeSocketWithoutEOS=!t,null===(n=this.processorNode)||void 0===n||null===(n=n.port)||void 0===n||n.postMessage("STOP"),null===(r=this.audioStream)||void 0===r||r.getAudioTracks()[0].removeEventListener("ended",function(){});case 9:case"end":return e.stop()}},e,this)})),function(e){return R.apply(this,arguments)})},{key:"IntentStartStream",value:function(){this.executor.Send("INTENT_START_STREAM")}},{key:"cleanup",value:function(){this.source.mediaStream.getAudioTracks()[0].stop(),this.source.disconnect(),this.processorNode.disconnect(),this.processorNode.port.close(),this.audioContext.close(),this.audioData=[]}},{key:"saveAudio",value:function(){var e=this.encodeWAV(),t=URL.createObjectURL(new Blob([e],{type:"audio/wav"}));this.log("Download Recording: ".concat(t))}},{key:"getBlob",value:function(){var e=this.encodeWAV();console.log(e);var t=new Blob([e],{type:"audio/wav"});return console.log(t),t}},{key:"encodeWAV",value:function(){var e=new DataView(new ArrayBuffer(2*this.audioData.length));this.audioData.forEach(function(t,i){e.setInt16(2*i,t,!0)});var t=e.buffer.byteLength,i=44+t,n=new DataView(new ArrayBuffer(i));n.setUint32(0,1380533830,!1),n.setUint32(4,i-8,!0),n.setUint32(8,1463899717,!1),n.setUint32(12,1718449184,!1),n.setUint32(16,16,!0),n.setUint16(20,1,!0),n.setUint16(22,1,!0),n.setUint32(24,16e3,!0),n.setUint32(28,32e3,!0),n.setUint16(32,2,!0),n.setUint16(34,16,!0),n.setUint32(36,1684108385,!1),n.setUint32(40,t,!0);for(var r=0;r<t;r++)n.setInt8(44+r,e.getInt8(r));return n}},{key:"log",value:function(e){if(this.enableLogs){var t="".concat((new Date).toLocaleTimeString()," Augnito: ").concat(e);console.log(t+"\n")}}}]),L=function(){function e(){var t,i,n,r,o=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{serverURL:"",enableLogs:!1,isDebug:!1,bufferInterval:1,pausedBufferInterval:1,EOS_Message:void 0,socketTimeoutInterval:void 0,shouldSendAudioDataSequence:!1,reconnectAudioDuration:0,shouldPreIntialiseRecorder:!1,shouldReadIntensity:!1,debounceDelay:300,switchToRegularSpeechProfile:!1,echoCancellation:void 0,noiseSuppression:void 0,autoGainControl:void 0},s=arguments.length>1?arguments[1]:void 0;if(v(this,e),e.instance)return e.instance;this.WebsocketURL=null!==(t=o.serverURL)&&void 0!==t?t:"",this.enableLogs=o.enableLogs,this.isDebug=o.isDebug,this.streamer=null,this.streamerNotStarted=!1,this.isStreamerStarting=!1,this.pendingStartStream=!1,this.heavyOp=s,this.bufferInterval=o.bufferInterval,this.pausedBufferInterval=o.pausedBufferInterval,this.eosMessage=o.EOS_Message,this.socketTimeoutInterval=o.socketTimeoutInterval,this.shouldSendAudioDataSequence=o.shouldSendAudioDataSequence,this.reconnectAudioDuration=null!==(i=o.reconnectAudioDuration)&&void 0!==i?i:0,this.shouldPreIntialiseRecorder=o.shouldPreIntialiseRecorder,this.switchToRegularSpeechProfile=null!==(n=o.switchToRegularSpeechProfile)&&void 0!==n&&n,this._echoCancellation=o.echoCancellation,this._noiseSuppression=o.noiseSuppression,this._autoGainControl=o.autoGainControl,this.shouldPreIntialiseRecorder&&(this.initialiseStreamer(),this.streamerNotStarted=!0),this.shouldReadIntensity=o.shouldReadIntensity,this.delay=null!==(r=o.debounceDelay)&&void 0!==r?r:300,this.toggleStartStopAudioStream=M(this.toggleStartStopAudioStream.bind(this),this.delay),this.togglePauseResumeAudioStream=M(this.togglePauseResumeAudioStream.bind(this),this.delay),this.needsDispose=!1,e.instance=this}return S(e,[{key:"echoCancellation",get:function(){return this._echoCancellation},set:function(e){this._echoCancellation=e,this.streamer&&(this.streamer.echoCancellation=e)}},{key:"noiseSuppression",get:function(){return this._noiseSuppression},set:function(e){this._noiseSuppression=e,this.streamer&&(this.streamer.noiseSuppression=e)}},{key:"autoGainControl",get:function(){return this._autoGainControl},set:function(e){this._autoGainControl=e,this.streamer&&(this.streamer.autoGainControl=e)}},{key:"initialiseStreamer",value:function(){this.streamer=new x(this.WebsocketURL,this.enableLogs,this.isDebug,this.bufferInterval,this.pausedBufferInterval,this.eosMessage,this.socketTimeoutInterval,this.shouldSendAudioDataSequence,this.reconnectAudioDuration,this.shouldPreIntialiseRecorder,this.shouldReadIntensity,this.switchToRegularSpeechProfile,this._echoCancellation,this._noiseSuppression,this._autoGainControl,this.heavyOp,this.onFinalResultCallback.bind(this),this.onPartialResultCallback.bind(this),this.onErrorCallback.bind(this),this.onStateChangedCallback.bind(this),this.onSessionEventCallback.bind(this),this.onOtherResultCallback.bind(this),this.onSpeechResponseCallback.bind(this),this.onIntensityCallback.bind(this),this.onJobStatusCallback.bind(this))}},{key:"updateIntentStartStream",value:function(){var e;this.pendingStartStream=!0,null===(e=this.streamer)||void 0===e||e.IntentStartStream()}},{key:"togglePauseResumeAudioStream",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:void 0;!this.streamer||this.streamerNotStarted?(t&&(this.WebsocketURL=t),this.startAudio(e)):this.streamer.IsPaused?this.resumeAudio():this.pauseAudio()}},{key:"toggleStartStopAudioStream",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:void 0;!this.streamer||this.streamerNotStarted?(t&&(this.WebsocketURL=t),this.startAudio(e)):this.stopAudio()}},{key:"startAudio",value:(t=p(d().mark(function e(t){return d().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(!this.isStreamerStarting){e.next=2;break}return e.abrupt("return");case 2:return this.isStreamerStarting=!0,this.shouldPreIntialiseRecorder&&this.streamer||this.initialiseStreamer(),e.prev=4,e.next=7,this.streamer.StartStream(t,this.WebsocketURL);case 7:e.sent?(this.streamerNotStarted=!1,this.log("Stream Started...")):this.streamer=null;case 9:return e.prev=9,this.isStreamerStarting=!1,e.finish(9);case 12:case"end":return e.stop()}},e,this,[[4,,9,12]])})),function(e){return t.apply(this,arguments)})},{key:"pauseAudio",value:function(){this.streamer.PauseStream(),this.log("Stream Paused...")}},{key:"resumeAudio",value:function(){this.streamer.ResumeStream(),this.enableLogs&&this.log("Stream Resumed...")}},{key:"stopAudio",value:function(){var e,t,i=this,n=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],r=arguments.length>1&&void 0!==arguments[1]&&arguments[1];(null!==(e=this.streamer)&&void 0!==e&&e.IsStreaming||r)&&(null===(t=this.streamer)||void 0===t||t.StopStream(n),this.streamer=null,this.log("Stream Stopped..."),this.shouldPreIntialiseRecorder&&setTimeout(function(){i.needsDispose?i.needsDispose=!1:(i.initialiseStreamer(),i.streamerNotStarted=!0)},500))}},{key:"getBlob",value:function(){var e=this.streamer.getBlob();return this.log("Blob Sent..."),e}},{key:"log",value:function(e){if(this.enableLogs){var t="".concat((new Date).toLocaleTimeString()," Augnito: ").concat(e);this.showLogCallback(t+"\n")}}},{key:"dispose",value:function(){var t;this.needsDispose=!0,null===(t=this.streamer)||void 0===t||t.StopStream(!1),this.streamer=null,e.instance=null}},{key:"onSessionEventCallback",value:function(e){this.onSessionEvent&&this.onSessionEvent(e)}},{key:"onStateChangedCallback",value:function(e){this.onStateChanged&&this.onStateChanged(e)}},{key:"onIntensityCallback",value:function(e){this.onIntensity&&this.onIntensity(e)}},{key:"onErrorCallback",value:function(e){this.onError&&this.onError(e)}},{key:"onPartialResultCallback",value:function(e){this.onPartialResult&&this.onPartialResult(e)}},{key:"onFinalResultCallback",value:function(e){this.onFinalResult&&this.onFinalResult(e)}},{key:"onOtherResultCallback",value:function(e){this.onOtherResults&&this.onOtherResults(e)}},{key:"onSpeechResponseCallback",value:function(e){this.onSpeechResponse&&this.onSpeechResponse(e)}},{key:"onJobStatusCallback",value:function(e){this.onJobStatus&&this.onJobStatus(e)}},{key:"showLogCallback",value:function(e){this.showLog&&this.showLog(e)}}]);var t}();function M(e,t){var i;return function(){for(var n=this,r=arguments.length,o=new Array(r),s=0;s<r;s++)o[s]=arguments[s];i&&clearTimeout(i),i=setTimeout(function(){return e.apply(n,o)},t)}}class J extends c{constructor(e){super(),Object.defineProperty(this,"_config",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"_baseUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._baseUrl=`https://${e.server}/pace/v1/sdk`}getURL(e){return`${this._baseUrl}${e}`}getNoteParams(){return e(this,void 0,void 0,function*(){const e=this.getURL("/noteparams"),t={SubscriptionCode:this._config.subscriptionCode,AccessKey:this._config.accessKey,UserTag:this._config.userTag};return yield this.makePostRequest(e,t)})}getSettingsConfigMaster(t){return e(this,void 0,void 0,function*(){const e=this.getURL("/configmaster"),i={SubscriptionCode:this._config.subscriptionCode,AccessKey:this._config.accessKey,UserTag:this._config.userTag,ConfigTypeId:t};return yield this.makePostRequest(e,i)})}getOrgConfigMapping(t){return e(this,void 0,void 0,function*(){const e=this.getURL("/configmapping").replace("/v1","/v2"),i={SubscriptionCode:this._config.subscriptionCode,AccessKey:this._config.accessKey,UserTag:this._config.userTag,ConfigTypeId:t};return yield this.makePostRequest(e,i)})}getUserConfigSettings(t){return e(this,void 0,void 0,function*(){const e=this.getURL("/userconfigmapping"),i={SubscriptionCode:this._config.subscriptionCode,AccessKey:this._config.accessKey,UserTag:this._config.userTag,ConfigTypeId:t};return yield this.makePostRequest(e,i)})}updateUserConfig(t){return e(this,void 0,void 0,function*(){const e=this.getURL("/userconfigmapping"),i={SubscriptionCode:this._config.subscriptionCode,AccessKey:this._config.accessKey,UserTag:this._config.userTag,UserConfigMapping:t};return yield this.makePatchRequest(e,i)})}getUserPreferences(){return e(this,void 0,void 0,function*(){const e=this.getURL("/getuserpreferences"),t={SubscriptionCode:this._config.subscriptionCode,AccessKey:this._config.accessKey,UserTag:this._config.userTag};return yield this.makePostRequest(e,t)})}updateUserPreference(t,i,n,r,o,s){return e(this,void 0,void 0,function*(){const e=this.getURL("/postuserpreferences"),a={SubscriptionCode:this._config.subscriptionCode,AccessKey:this._config.accessKey,UserTag:this._config.userTag,UserPreferences:{AutomaticallyGenerateTranscript:t,PreferredTranscriptionLanguage:i,HighlightMedicalTerms:n,DisplayPatientContext:r,NoteOutputStyle:o,NoteOutputVerbosity:s}};return yield this.makePostRequest(e,a)})}}const K="Invalid user details, please check again",j="Subscription is not valid.",W="invalid request. Please make sure AccessKey, SubscriptionCode and UserTag is sent along with the request",G="Active seat is not available for user",B="Unable to fetch account details, please try again.",V="Unable to fetch job details, please try again.",F="Job not reconnectable",z="Timeout exceeded",q="Rate Limit Exceeded, Please try again in sometime!",H="Audio Signal is power very LOW, Mic might be muted",$="Job Id is empty",Y="Page Size is undefined",Q="Note Data is empty",X="Job Name is empty",Z="Patient Context is empty",ee="Mic permission denied",te="Microphone is muted",ie="Audio track ended. Possibly the mic was unplugged",ne="Internet is not available. Try again later.",re="Feedback is not enabled. Please contact administrator for more details.",oe="Automatic Transcription is not enabled for the organisation";class se{static isBrowserOnline(){return"undefined"!=typeof navigator&&!0===navigator.onLine}static isValidHttpUrl(e){if("string"!=typeof e||e.length>2048)return!1;try{const t=new URL(e);return("http:"===t.protocol||"https:"===t.protocol)&&(!t.username&&!t.password)}catch(e){return!1}}static hasInternetConnection(){return e(this,arguments,void 0,function*(e={url:null,timeoutMs:null}){var t=e.url||se.DEFAULT_URL;const i=e.timeoutMs||se.DEFAULT_TIMEOUT;if(!se.isBrowserOnline())return!1;se.isValidHttpUrl(t)||(t=se.DEFAULT_URL);const n=new AbortController,r=setTimeout(()=>n.abort(),i);try{return yield fetch(t,{method:"HEAD",mode:"no-cors",cache:"no-cache",signal:n.signal}),!0}catch(e){return!1}finally{clearTimeout(r)}})}static isOnline(t){return e(this,void 0,void 0,function*(){return se.hasInternetConnection(t)})}}Object.defineProperty(se,"DEFAULT_URL",{enumerable:!0,configurable:!0,writable:!0,value:"https://www.google.com/favicon.ico"}),Object.defineProperty(se,"DEFAULT_TIMEOUT",{enumerable:!0,configurable:!0,writable:!0,value:5e3});class ae{constructor(e){Object.defineProperty(this,"_logTag",{enumerable:!0,configurable:!0,writable:!0,value:"Augnito-Ambient"}),Object.defineProperty(this,"_ambientRestAPI",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_ambientPaceAPI",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"config",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"enableLog",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shouldReadAudioIntensity",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"recorderIns",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"forceStopAudio",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_isRecording",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"echoCancellation",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"noiseSuppression",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"autoGainControl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onJobCreated",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onStateChanged",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onError",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onOtherResult",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onIntensityValue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onIdleMic",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onSoapNoteGenerated",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onTranscriptGenerated",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onCodesGenerated",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onJobStatus",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._amb