assemblyai 4.24.0 → 4.25.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -65,7 +65,7 @@
65
65
  defaultUserAgentString += navigator.userAgent;
66
66
  }
67
67
  const defaultUserAgent = {
68
- sdk: { name: "JavaScript", version: "4.24.0" },
68
+ sdk: { name: "JavaScript", version: "4.25.1" },
69
69
  };
70
70
  if (typeof process !== "undefined") {
71
71
  if (process.versions.node && defaultUserAgentString.indexOf("Node") === -1) {
@@ -950,6 +950,12 @@ Learn more at https://github.com/AssemblyAI/assemblyai-node-sdk/blob/main/docs/c
950
950
  if (this.params.inactivityTimeout !== undefined) {
951
951
  searchParams.set("inactivity_timeout", this.params.inactivityTimeout.toString());
952
952
  }
953
+ if (this.params.speakerLabels !== undefined) {
954
+ searchParams.set("speaker_labels", this.params.speakerLabels.toString());
955
+ }
956
+ if (this.params.maxSpeakers !== undefined) {
957
+ searchParams.set("max_speakers", this.params.maxSpeakers.toString());
958
+ }
953
959
  url.search = searchParams.toString();
954
960
  return url;
955
961
  }
@@ -994,7 +1000,7 @@ Learn more at https://github.com/AssemblyAI/assemblyai-node-sdk/blob/main/docs/c
994
1000
  (_d = (_c = this.listeners).error) === null || _d === void 0 ? void 0 : _d.call(_c, new Error(event.message));
995
1001
  };
996
1002
  this.socket.onmessage = ({ data }) => {
997
- var _a, _b, _c, _d, _e, _f, _g;
1003
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j;
998
1004
  const message = JSON.parse(data.toString());
999
1005
  if ("error" in message) {
1000
1006
  (_b = (_a = this.listeners).error) === null || _b === void 0 ? void 0 : _b.call(_a, new StreamingError(message.error));
@@ -1010,8 +1016,12 @@ Learn more at https://github.com/AssemblyAI/assemblyai-node-sdk/blob/main/docs/c
1010
1016
  (_f = (_e = this.listeners).turn) === null || _f === void 0 ? void 0 : _f.call(_e, message);
1011
1017
  break;
1012
1018
  }
1019
+ case "SpeechStarted": {
1020
+ (_h = (_g = this.listeners).speechStarted) === null || _h === void 0 ? void 0 : _h.call(_g, message);
1021
+ break;
1022
+ }
1013
1023
  case "Termination": {
1014
- (_g = this.sessionTerminatedResolve) === null || _g === void 0 ? void 0 : _g.call(this);
1024
+ (_j = this.sessionTerminatedResolve) === null || _j === void 0 ? void 0 : _j.call(this);
1015
1025
  break;
1016
1026
  }
1017
1027
  }
@@ -1 +1 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).assemblyai={})}(this,(function(e){"use strict";function t(e,t,s,i){return new(s||(s=Promise))((function(n,r){function o(e){try{c(i.next(e))}catch(e){r(e)}}function a(e){try{c(i.throw(e))}catch(e){r(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,a)}c((i=i.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;const s={cache:"no-store"};let i="";"undefined"!=typeof navigator&&navigator.userAgent&&(i+=navigator.userAgent);const n={sdk:{name:"JavaScript",version:"4.24.0"}};"undefined"!=typeof process&&(process.versions.node&&-1===i.indexOf("Node")&&(n.runtime_env={name:"Node",version:process.versions.node}),process.versions.bun&&-1===i.indexOf("Bun")&&(n.runtime_env={name:"Bun",version:process.versions.bun})),"undefined"!=typeof Deno&&process.versions.bun&&-1===i.indexOf("Deno")&&(n.runtime_env={name:"Deno",version:Deno.version.deno});class r{constructor(e){var t;this.params=e,!1===e.userAgent?this.userAgent=void 0:this.userAgent=(t=e.userAgent||{},i+(!1===t?"":" AssemblyAI/1.0 ("+Object.entries(Object.assign(Object.assign({},n),t)).map((([e,t])=>t?`${e}=${t.name}/${t.version}`:"")).join(" ")+")"))}fetch(e,i){return t(this,void 0,void 0,(function*(){i=Object.assign(Object.assign({},s),i);let t={Authorization:this.params.apiKey,"Content-Type":"application/json"};(null==s?void 0:s.headers)&&(t=Object.assign(Object.assign({},t),s.headers)),(null==i?void 0:i.headers)&&(t=Object.assign(Object.assign({},t),i.headers)),this.userAgent&&(t["User-Agent"]=this.userAgent,"undefined"!=typeof window&&"chrome"in window&&(t["AssemblyAI-Agent"]=this.userAgent)),i.headers=t,e.startsWith("http")||(e=this.params.baseUrl+e);const n=yield fetch(e,i);if(n.status>=400){let e;const t=yield n.text();if(t){try{e=JSON.parse(t)}catch(e){}if(null==e?void 0:e.error)throw new Error(e.error);throw new Error(t)}throw new Error(`HTTP Error: ${n.status} ${n.statusText}`)}return n}))}fetchJson(e,s){return t(this,void 0,void 0,(function*(){return(yield this.fetch(e,s)).json()}))}}class o extends r{summary(e,t){return this.fetchJson("/lemur/v3/generate/summary",{method:"POST",body:JSON.stringify(e),signal:t})}questionAnswer(e,t){return this.fetchJson("/lemur/v3/generate/question-answer",{method:"POST",body:JSON.stringify(e),signal:t})}actionItems(e,t){return this.fetchJson("/lemur/v3/generate/action-items",{method:"POST",body:JSON.stringify(e),signal:t})}task(e,t){return this.fetchJson("/lemur/v3/generate/task",{method:"POST",body:JSON.stringify(e),signal:t})}getResponse(e,t){return this.fetchJson(`/lemur/v3/${e}`,{signal:t})}purgeRequestData(e,t){return this.fetchJson(`/lemur/v3/${e}`,{method:"DELETE",signal:t})}}const{WritableStream:a}="undefined"!=typeof window?window:"undefined"!=typeof global?global:globalThis;var c,l;const d=null!==(l=null!==(c=null!==WebSocket&&void 0!==WebSocket?WebSocket:null===global||void 0===global?void 0:global.WebSocket)&&void 0!==c?c:null===window||void 0===window?void 0:window.WebSocket)&&void 0!==l?l:null===self||void 0===self?void 0:self.WebSocket,h=(e,t)=>t?new d(e,t):new d(e),u={[4e3]:"Sample rate must be a positive integer",[4001]:"Not Authorized",[4002]:"Insufficient funds",[4003]:"This feature is paid-only and requires you to add a credit card. Please visit https://app.assemblyai.com/ to add a credit card to your account.",[4004]:"Session ID does not exist",[4008]:"Session has expired",[4010]:"Session is closed",[4029]:"Rate limited",[4030]:"Unique session violation",[4031]:"Session Timeout",[4032]:"Audio too short",[4033]:"Audio too long",[4034]:"Audio too small to transcode",[4100]:"Bad JSON",[4101]:"Bad schema",[4102]:"Too many streams",[4103]:"This session has been reconnected. This WebSocket is no longer valid.",[1013]:"Reconnect attempts exhausted",[4104]:"Could not parse word boost parameter"};class p extends Error{}const m={[4e3]:"Sample rate must be a positive integer",[4001]:"Not Authorized",[4002]:"Insufficient funds",[4003]:"This feature is paid-only and requires you to add a credit card. Please visit https://app.assemblyai.com/ to add a credit card to your account.",[4004]:"Session ID does not exist",[4008]:"Session has expired",[4010]:"Session is closed",[4029]:"Rate limited",[4030]:"Unique session violation",[4031]:"Session Timeout",[4032]:"Audio too short",[4033]:"Audio too long",[4034]:"Audio too small to transcode",[4101]:"Bad schema",[4102]:"Too many streams",[4103]:"This session has been reconnected. This WebSocket is no longer valid."};class f extends Error{}const v='{"terminate_session":true}';class y{constructor(e){var t,s;if(this.listeners={},this.realtimeUrl=null!==(t=e.realtimeUrl)&&void 0!==t?t:"wss://api.assemblyai.com/v2/realtime/ws",this.sampleRate=null!==(s=e.sampleRate)&&void 0!==s?s:16e3,this.wordBoost=e.wordBoost,this.encoding=e.encoding,this.endUtteranceSilenceThreshold=e.endUtteranceSilenceThreshold,this.disablePartialTranscripts=e.disablePartialTranscripts,"token"in e&&e.token&&(this.token=e.token),"apiKey"in e&&e.apiKey&&(this.apiKey=e.apiKey),!this.token&&!this.apiKey)throw new Error("API key or temporary token is required.")}connectionUrl(){const e=new URL(this.realtimeUrl);if("wss:"!==e.protocol)throw new Error("Invalid protocol, must be wss");const t=new URLSearchParams;return this.token&&t.set("token",this.token),t.set("sample_rate",this.sampleRate.toString()),this.wordBoost&&this.wordBoost.length>0&&t.set("word_boost",JSON.stringify(this.wordBoost)),this.encoding&&t.set("encoding",this.encoding),t.set("enable_extra_session_information","true"),this.disablePartialTranscripts&&t.set("disable_partial_transcripts",this.disablePartialTranscripts.toString()),e.search=t.toString(),e}on(e,t){this.listeners[e]=t}connect(){return new Promise((e=>{if(this.socket)throw new Error("Already connected");const t=this.connectionUrl();this.token?this.socket=h(t.toString()):(console.warn("API key authentication is not supported for the RealtimeTranscriber in browser environment. Use temporary token authentication instead.\nLearn more at https://github.com/AssemblyAI/assemblyai-node-sdk/blob/main/docs/compat.md#browser-compatibility."),this.socket=h(t.toString(),{headers:{Authorization:this.apiKey}})),this.socket.binaryType="arraybuffer",this.socket.onopen=()=>{void 0!==this.endUtteranceSilenceThreshold&&null!==this.endUtteranceSilenceThreshold&&this.configureEndUtteranceSilenceThreshold(this.endUtteranceSilenceThreshold)},this.socket.onclose=({code:e,reason:t})=>{var s,i;t||e in u&&(t=u[e]),null===(i=(s=this.listeners).close)||void 0===i||i.call(s,e,t)},this.socket.onerror=e=>{var t,s,i,n;e.error?null===(s=(t=this.listeners).error)||void 0===s||s.call(t,e.error):null===(n=(i=this.listeners).error)||void 0===n||n.call(i,new Error(e.message))},this.socket.onmessage=({data:t})=>{var s,i,n,r,o,a,c,l,d,h,u,m,f,v,y;const g=JSON.parse(t.toString());if("error"in g)null===(i=(s=this.listeners).error)||void 0===i||i.call(s,new p(g.error));else switch(g.message_type){case"SessionBegins":{const t={sessionId:g.session_id,expiresAt:new Date(g.expires_at)};e(t),null===(r=(n=this.listeners).open)||void 0===r||r.call(n,t);break}case"PartialTranscript":g.created=new Date(g.created),null===(a=(o=this.listeners).transcript)||void 0===a||a.call(o,g),null===(l=(c=this.listeners)["transcript.partial"])||void 0===l||l.call(c,g);break;case"FinalTranscript":g.created=new Date(g.created),null===(h=(d=this.listeners).transcript)||void 0===h||h.call(d,g),null===(m=(u=this.listeners)["transcript.final"])||void 0===m||m.call(u,g);break;case"SessionInformation":null===(v=(f=this.listeners).session_information)||void 0===v||v.call(f,g);break;case"SessionTerminated":null===(y=this.sessionTerminatedResolve)||void 0===y||y.call(this)}}}))}sendAudio(e){this.send(e)}stream(){return new a({write:e=>{this.sendAudio(e)}})}forceEndUtterance(){this.send('{"force_end_utterance":true}')}configureEndUtteranceSilenceThreshold(e){this.send(`{"end_utterance_silence_threshold":${e}}`)}send(e){if(!this.socket||this.socket.readyState!==this.socket.OPEN)throw new Error("Socket is not open for communication");this.socket.send(e)}close(){return t(this,arguments,void 0,(function*(e=!0){var t;if(this.socket){if(this.socket.readyState===this.socket.OPEN)if(e){const e=new Promise((e=>{this.sessionTerminatedResolve=e}));this.socket.send(v),yield e}else this.socket.send(v);(null===(t=this.socket)||void 0===t?void 0:t.removeAllListeners)&&this.socket.removeAllListeners(),this.socket.close()}this.listeners={},this.socket=void 0}))}}class g extends r{constructor(e){super(e),this.rtFactoryParams=e}createService(e){return this.transcriber(e)}transcriber(e){const t=Object.assign({},e);return t.token||t.apiKey||(t.apiKey=this.rtFactoryParams.apiKey),new y(t)}createTemporaryToken(e){return t(this,void 0,void 0,(function*(){return(yield this.fetchJson("/v2/realtime/token",{method:"POST",body:JSON.stringify(e)})).token}))}}function b(e){return e.startsWith("http")||e.startsWith("https")||e.startsWith("data:")?null:e.startsWith("file://")?e.substring(7):e.startsWith("file:")?e.substring(5):e}class w extends r{constructor(e,t){super(e),this.files=t}transcribe(e,s){return t(this,void 0,void 0,(function*(){const t=yield this.submit(e);return yield this.waitUntilReady(t.id,s)}))}submit(e){return t(this,void 0,void 0,(function*(){let t,s;if("audio"in e){const{audio:i}=e,n=function(e,t){var s={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(s[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(i=Object.getOwnPropertySymbols(e);n<i.length;n++)t.indexOf(i[n])<0&&Object.prototype.propertyIsEnumerable.call(e,i[n])&&(s[i[n]]=e[i[n]])}return s}(e,["audio"]);if("string"==typeof i){const e=b(i);t=null!==e?yield this.files.upload(e):i.startsWith("data:")?yield this.files.upload(i):i}else t=yield this.files.upload(i);s=Object.assign(Object.assign({},n),{audio_url:t})}else s=e;return yield this.fetchJson("/v2/transcript",{method:"POST",body:JSON.stringify(s)})}))}create(e,s){return t(this,void 0,void 0,(function*(){var t;const i=b(e.audio_url);if(null!==i){const t=yield this.files.upload(i);e.audio_url=t}const n=yield this.fetchJson("/v2/transcript",{method:"POST",body:JSON.stringify(e)});return null===(t=null==s?void 0:s.poll)||void 0===t||t?yield this.waitUntilReady(n.id,s):n}))}waitUntilReady(e,s){return t(this,void 0,void 0,(function*(){var t,i;const n=null!==(t=null==s?void 0:s.pollingInterval)&&void 0!==t?t:3e3,r=null!==(i=null==s?void 0:s.pollingTimeout)&&void 0!==i?i:-1,o=Date.now();for(;;){const t=yield this.get(e);if("completed"===t.status||"error"===t.status)return t;if(r>0&&Date.now()-o>r)throw new Error("Polling timeout");yield new Promise((e=>setTimeout(e,n)))}}))}get(e){return this.fetchJson(`/v2/transcript/${e}`)}list(e){return t(this,void 0,void 0,(function*(){let t="/v2/transcript";"string"==typeof e?t=e:e&&(t=`${t}?${new URLSearchParams(Object.keys(e).map((t=>{var s;return[t,(null===(s=e[t])||void 0===s?void 0:s.toString())||""]})))}`);const s=yield this.fetchJson(t);for(const e of s.transcripts)e.created=new Date(e.created),e.completed&&(e.completed=new Date(e.completed));return s}))}delete(e){return this.fetchJson(`/v2/transcript/${e}`,{method:"DELETE"})}wordSearch(e,t){const s=new URLSearchParams({words:t.join(",")});return this.fetchJson(`/v2/transcript/${e}/word-search?${s.toString()}`)}sentences(e){return this.fetchJson(`/v2/transcript/${e}/sentences`)}paragraphs(e){return this.fetchJson(`/v2/transcript/${e}/paragraphs`)}subtitles(e){return t(this,arguments,void 0,(function*(e,t="srt",s){let i=`/v2/transcript/${e}/${t}`;if(s){const e=new URLSearchParams;e.set("chars_per_caption",s.toString()),i+=`?${e.toString()}`}const n=yield this.fetch(i);return yield n.text()}))}redactions(e){return this.redactedAudio(e)}redactedAudio(e){return this.fetchJson(`/v2/transcript/${e}/redacted-audio`)}redactedAudioFile(e){return t(this,void 0,void 0,(function*(){const{redacted_audio_url:t,status:s}=yield this.redactedAudio(e);if("redacted_audio_ready"!==s)throw new Error(`Redacted audio status is ${s}`);const i=yield fetch(t);if(!i.ok)throw new Error(`Failed to fetch redacted audio: ${i.statusText}`);return{arrayBuffer:i.arrayBuffer.bind(i),blob:i.blob.bind(i),body:i.body,bodyUsed:i.bodyUsed}}))}}class S extends r{upload(e){return t(this,void 0,void 0,(function*(){let s;s="string"==typeof e?e.startsWith("data:")?function(e){const t=e.split(","),s=t[0].match(/:(.*?);/)[1],i=atob(t[1]);let n=i.length;const r=new Uint8Array(n);for(;n--;)r[n]=i.charCodeAt(n);return new Blob([r],{type:s})}(e):yield function(e){return t(this,void 0,void 0,(function*(){throw new Error("Interacting with the file system is not supported in this environment.")}))}():e;return(yield this.fetchJson("/v2/upload",{method:"POST",body:s,headers:{"Content-Type":"application/octet-stream"},duplex:"half"})).upload_url}))}}const k='{"type":"Terminate"}';class T{constructor(e){if(this.listeners={},this.params=Object.assign(Object.assign({},e),{websocketBaseUrl:e.websocketBaseUrl||"wss://streaming.assemblyai.com/v3/ws"}),"token"in e&&e.token&&(this.token=e.token),"apiKey"in e&&e.apiKey&&(this.apiKey=e.apiKey),!this.token&&!this.apiKey)throw new Error("API key or temporary token is required.")}connectionUrl(){var e;const t=new URL(null!==(e=this.params.websocketBaseUrl)&&void 0!==e?e:"");if("wss:"!==t.protocol)throw new Error("Invalid protocol, must be wss");const s=new URLSearchParams;return this.token&&s.set("token",this.token),s.set("sample_rate",this.params.sampleRate.toString()),this.params.endOfTurnConfidenceThreshold&&s.set("end_of_turn_confidence_threshold",this.params.endOfTurnConfidenceThreshold.toString()),this.params.minTurnSilence?s.set("min_turn_silence",this.params.minTurnSilence.toString()):this.params.minEndOfTurnSilenceWhenConfident&&(console.warn("[Deprecation Warning] `minEndOfTurnSilenceWhenConfident` is deprecated and will be removed in a future release. Please use `minTurnSilence` instead."),s.set("min_end_of_turn_silence_when_confident",this.params.minEndOfTurnSilenceWhenConfident.toString())),this.params.maxTurnSilence&&s.set("max_turn_silence",this.params.maxTurnSilence.toString()),void 0!==this.params.vadThreshold&&s.set("vad_threshold",this.params.vadThreshold.toString()),this.params.formatTurns&&s.set("format_turns",this.params.formatTurns.toString()),this.params.encoding&&s.set("encoding",this.params.encoding.toString()),this.params.keytermsPrompt?s.set("keyterms_prompt",JSON.stringify(this.params.keytermsPrompt)):this.params.keyterms&&(console.warn("[Deprecation Warning] `keyterms` is deprecated and will be removed in a future release. Please use `keytermsPrompt` instead."),s.set("keyterms_prompt",JSON.stringify(this.params.keyterms))),this.params.prompt&&s.set("prompt",this.params.prompt),this.params.filterProfanity&&s.set("filter_profanity",this.params.filterProfanity.toString()),this.params.speechModel&&("u3-pro"===this.params.speechModel&&console.warn("[Deprecation Warning] The speech model `u3-pro` is deprecated and will be removed in a future release. Please use `u3-rt-pro` instead."),s.set("speech_model",this.params.speechModel.toString())),void 0!==this.params.languageDetection&&s.set("language_detection",this.params.languageDetection.toString()),void 0!==this.params.inactivityTimeout&&s.set("inactivity_timeout",this.params.inactivityTimeout.toString()),t.search=s.toString(),t}on(e,t){this.listeners[e]=t}connect(){return new Promise((e=>{if(this.socket)throw new Error("Already connected");const t=this.connectionUrl();this.token?this.socket=h(t.toString()):(console.warn("API key authentication is not supported for the StreamingTranscriber in browser environment. Use temporary token authentication instead.\nLearn more at https://github.com/AssemblyAI/assemblyai-node-sdk/blob/main/docs/compat.md#browser-compatibility."),this.socket=h(t.toString(),{headers:{Authorization:this.apiKey}})),this.socket.binaryType="arraybuffer",this.socket.onopen=()=>{},this.socket.onclose=({code:e,reason:t})=>{var s,i;t||e in m&&(t=m[e]),null===(i=(s=this.listeners).close)||void 0===i||i.call(s,e,t)},this.socket.onerror=e=>{var t,s,i,n;e.error?null===(s=(t=this.listeners).error)||void 0===s||s.call(t,e.error):null===(n=(i=this.listeners).error)||void 0===n||n.call(i,new Error(e.message))},this.socket.onmessage=({data:t})=>{var s,i,n,r,o,a,c;const l=JSON.parse(t.toString());if("error"in l)null===(i=(s=this.listeners).error)||void 0===i||i.call(s,new f(l.error));else switch(l.type){case"Begin":e(l),null===(r=(n=this.listeners).open)||void 0===r||r.call(n,l);break;case"Turn":null===(a=(o=this.listeners).turn)||void 0===a||a.call(o,l);break;case"Termination":null===(c=this.sessionTerminatedResolve)||void 0===c||c.call(this)}}}))}stream(){return new a({write:e=>{this.sendAudio(e)}})}sendAudio(e){this.send(e)}updateConfiguration(e){const t=Object.assign({type:"UpdateConfiguration"},e);this.send(JSON.stringify(t))}forceEndpoint(){this.send(JSON.stringify({type:"ForceEndpoint"}))}send(e){if(!this.socket||this.socket.readyState!==this.socket.OPEN)throw new Error("Socket is not open for communication");this.socket.send(e)}close(){return t(this,arguments,void 0,(function*(e=!0){var t;if(this.socket){if(this.socket.readyState===this.socket.OPEN)if(e){const e=new Promise((e=>{this.sessionTerminatedResolve=e}));this.socket.send(k),yield e}else this.socket.send(k);(null===(t=this.socket)||void 0===t?void 0:t.removeAllListeners)&&this.socket.removeAllListeners(),this.socket.close()}this.listeners={},this.socket=void 0}))}}class O extends r{constructor(e){super(e),this.baseServiceParams=e}transcriber(e){const t=Object.assign({},e);return t.token||t.apiKey||(t.apiKey=this.baseServiceParams.apiKey),new T(t)}createTemporaryToken(e){return t(this,void 0,void 0,(function*(){const t=new URLSearchParams;Object.entries(e).forEach((([e,s])=>{null!=s&&t.append(e,String(s))}));const s=t.toString(),i=s?`/v3/token?${s}`:"/v3/token";return(yield this.fetchJson(i,{method:"GET"})).token}))}}e.AssemblyAI=class{constructor(e){e.baseUrl=e.baseUrl||"https://api.assemblyai.com",e.baseUrl&&e.baseUrl.endsWith("/")&&(e.baseUrl=e.baseUrl.slice(0,-1)),this.files=new S(e),this.transcripts=new w(e,this.files),this.lemur=new o(e),this.realtime=new g(e),this.streaming=new O(Object.assign(Object.assign({},e),{baseUrl:e.streamingBaseUrl||"https://streaming.assemblyai.com"}))}},e.FileService=S,e.LemurService=o,e.RealtimeService=class extends y{},e.RealtimeServiceFactory=class extends g{},e.RealtimeTranscriber=y,e.RealtimeTranscriberFactory=g,e.StreamingTranscriber=T,e.TranscriptService=w}));
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).assemblyai={})}(this,(function(e){"use strict";function t(e,t,s,i){return new(s||(s=Promise))((function(r,n){function o(e){try{c(i.next(e))}catch(e){n(e)}}function a(e){try{c(i.throw(e))}catch(e){n(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,a)}c((i=i.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;const s={cache:"no-store"};let i="";"undefined"!=typeof navigator&&navigator.userAgent&&(i+=navigator.userAgent);const r={sdk:{name:"JavaScript",version:"4.25.1"}};"undefined"!=typeof process&&(process.versions.node&&-1===i.indexOf("Node")&&(r.runtime_env={name:"Node",version:process.versions.node}),process.versions.bun&&-1===i.indexOf("Bun")&&(r.runtime_env={name:"Bun",version:process.versions.bun})),"undefined"!=typeof Deno&&process.versions.bun&&-1===i.indexOf("Deno")&&(r.runtime_env={name:"Deno",version:Deno.version.deno});class n{constructor(e){var t;this.params=e,!1===e.userAgent?this.userAgent=void 0:this.userAgent=(t=e.userAgent||{},i+(!1===t?"":" AssemblyAI/1.0 ("+Object.entries(Object.assign(Object.assign({},r),t)).map((([e,t])=>t?`${e}=${t.name}/${t.version}`:"")).join(" ")+")"))}fetch(e,i){return t(this,void 0,void 0,(function*(){i=Object.assign(Object.assign({},s),i);let t={Authorization:this.params.apiKey,"Content-Type":"application/json"};(null==s?void 0:s.headers)&&(t=Object.assign(Object.assign({},t),s.headers)),(null==i?void 0:i.headers)&&(t=Object.assign(Object.assign({},t),i.headers)),this.userAgent&&(t["User-Agent"]=this.userAgent,"undefined"!=typeof window&&"chrome"in window&&(t["AssemblyAI-Agent"]=this.userAgent)),i.headers=t,e.startsWith("http")||(e=this.params.baseUrl+e);const r=yield fetch(e,i);if(r.status>=400){let e;const t=yield r.text();if(t){try{e=JSON.parse(t)}catch(e){}if(null==e?void 0:e.error)throw new Error(e.error);throw new Error(t)}throw new Error(`HTTP Error: ${r.status} ${r.statusText}`)}return r}))}fetchJson(e,s){return t(this,void 0,void 0,(function*(){return(yield this.fetch(e,s)).json()}))}}class o extends n{summary(e,t){return this.fetchJson("/lemur/v3/generate/summary",{method:"POST",body:JSON.stringify(e),signal:t})}questionAnswer(e,t){return this.fetchJson("/lemur/v3/generate/question-answer",{method:"POST",body:JSON.stringify(e),signal:t})}actionItems(e,t){return this.fetchJson("/lemur/v3/generate/action-items",{method:"POST",body:JSON.stringify(e),signal:t})}task(e,t){return this.fetchJson("/lemur/v3/generate/task",{method:"POST",body:JSON.stringify(e),signal:t})}getResponse(e,t){return this.fetchJson(`/lemur/v3/${e}`,{signal:t})}purgeRequestData(e,t){return this.fetchJson(`/lemur/v3/${e}`,{method:"DELETE",signal:t})}}const{WritableStream:a}="undefined"!=typeof window?window:"undefined"!=typeof global?global:globalThis;var c,l;const d=null!==(l=null!==(c=null!==WebSocket&&void 0!==WebSocket?WebSocket:null===global||void 0===global?void 0:global.WebSocket)&&void 0!==c?c:null===window||void 0===window?void 0:window.WebSocket)&&void 0!==l?l:null===self||void 0===self?void 0:self.WebSocket,h=(e,t)=>t?new d(e,t):new d(e),u={[4e3]:"Sample rate must be a positive integer",[4001]:"Not Authorized",[4002]:"Insufficient funds",[4003]:"This feature is paid-only and requires you to add a credit card. Please visit https://app.assemblyai.com/ to add a credit card to your account.",[4004]:"Session ID does not exist",[4008]:"Session has expired",[4010]:"Session is closed",[4029]:"Rate limited",[4030]:"Unique session violation",[4031]:"Session Timeout",[4032]:"Audio too short",[4033]:"Audio too long",[4034]:"Audio too small to transcode",[4100]:"Bad JSON",[4101]:"Bad schema",[4102]:"Too many streams",[4103]:"This session has been reconnected. This WebSocket is no longer valid.",[1013]:"Reconnect attempts exhausted",[4104]:"Could not parse word boost parameter"};class p extends Error{}const m={[4e3]:"Sample rate must be a positive integer",[4001]:"Not Authorized",[4002]:"Insufficient funds",[4003]:"This feature is paid-only and requires you to add a credit card. Please visit https://app.assemblyai.com/ to add a credit card to your account.",[4004]:"Session ID does not exist",[4008]:"Session has expired",[4010]:"Session is closed",[4029]:"Rate limited",[4030]:"Unique session violation",[4031]:"Session Timeout",[4032]:"Audio too short",[4033]:"Audio too long",[4034]:"Audio too small to transcode",[4101]:"Bad schema",[4102]:"Too many streams",[4103]:"This session has been reconnected. This WebSocket is no longer valid."};class f extends Error{}const v='{"terminate_session":true}';class y{constructor(e){var t,s;if(this.listeners={},this.realtimeUrl=null!==(t=e.realtimeUrl)&&void 0!==t?t:"wss://api.assemblyai.com/v2/realtime/ws",this.sampleRate=null!==(s=e.sampleRate)&&void 0!==s?s:16e3,this.wordBoost=e.wordBoost,this.encoding=e.encoding,this.endUtteranceSilenceThreshold=e.endUtteranceSilenceThreshold,this.disablePartialTranscripts=e.disablePartialTranscripts,"token"in e&&e.token&&(this.token=e.token),"apiKey"in e&&e.apiKey&&(this.apiKey=e.apiKey),!this.token&&!this.apiKey)throw new Error("API key or temporary token is required.")}connectionUrl(){const e=new URL(this.realtimeUrl);if("wss:"!==e.protocol)throw new Error("Invalid protocol, must be wss");const t=new URLSearchParams;return this.token&&t.set("token",this.token),t.set("sample_rate",this.sampleRate.toString()),this.wordBoost&&this.wordBoost.length>0&&t.set("word_boost",JSON.stringify(this.wordBoost)),this.encoding&&t.set("encoding",this.encoding),t.set("enable_extra_session_information","true"),this.disablePartialTranscripts&&t.set("disable_partial_transcripts",this.disablePartialTranscripts.toString()),e.search=t.toString(),e}on(e,t){this.listeners[e]=t}connect(){return new Promise((e=>{if(this.socket)throw new Error("Already connected");const t=this.connectionUrl();this.token?this.socket=h(t.toString()):(console.warn("API key authentication is not supported for the RealtimeTranscriber in browser environment. Use temporary token authentication instead.\nLearn more at https://github.com/AssemblyAI/assemblyai-node-sdk/blob/main/docs/compat.md#browser-compatibility."),this.socket=h(t.toString(),{headers:{Authorization:this.apiKey}})),this.socket.binaryType="arraybuffer",this.socket.onopen=()=>{void 0!==this.endUtteranceSilenceThreshold&&null!==this.endUtteranceSilenceThreshold&&this.configureEndUtteranceSilenceThreshold(this.endUtteranceSilenceThreshold)},this.socket.onclose=({code:e,reason:t})=>{var s,i;t||e in u&&(t=u[e]),null===(i=(s=this.listeners).close)||void 0===i||i.call(s,e,t)},this.socket.onerror=e=>{var t,s,i,r;e.error?null===(s=(t=this.listeners).error)||void 0===s||s.call(t,e.error):null===(r=(i=this.listeners).error)||void 0===r||r.call(i,new Error(e.message))},this.socket.onmessage=({data:t})=>{var s,i,r,n,o,a,c,l,d,h,u,m,f,v,y;const g=JSON.parse(t.toString());if("error"in g)null===(i=(s=this.listeners).error)||void 0===i||i.call(s,new p(g.error));else switch(g.message_type){case"SessionBegins":{const t={sessionId:g.session_id,expiresAt:new Date(g.expires_at)};e(t),null===(n=(r=this.listeners).open)||void 0===n||n.call(r,t);break}case"PartialTranscript":g.created=new Date(g.created),null===(a=(o=this.listeners).transcript)||void 0===a||a.call(o,g),null===(l=(c=this.listeners)["transcript.partial"])||void 0===l||l.call(c,g);break;case"FinalTranscript":g.created=new Date(g.created),null===(h=(d=this.listeners).transcript)||void 0===h||h.call(d,g),null===(m=(u=this.listeners)["transcript.final"])||void 0===m||m.call(u,g);break;case"SessionInformation":null===(v=(f=this.listeners).session_information)||void 0===v||v.call(f,g);break;case"SessionTerminated":null===(y=this.sessionTerminatedResolve)||void 0===y||y.call(this)}}}))}sendAudio(e){this.send(e)}stream(){return new a({write:e=>{this.sendAudio(e)}})}forceEndUtterance(){this.send('{"force_end_utterance":true}')}configureEndUtteranceSilenceThreshold(e){this.send(`{"end_utterance_silence_threshold":${e}}`)}send(e){if(!this.socket||this.socket.readyState!==this.socket.OPEN)throw new Error("Socket is not open for communication");this.socket.send(e)}close(){return t(this,arguments,void 0,(function*(e=!0){var t;if(this.socket){if(this.socket.readyState===this.socket.OPEN)if(e){const e=new Promise((e=>{this.sessionTerminatedResolve=e}));this.socket.send(v),yield e}else this.socket.send(v);(null===(t=this.socket)||void 0===t?void 0:t.removeAllListeners)&&this.socket.removeAllListeners(),this.socket.close()}this.listeners={},this.socket=void 0}))}}class g extends n{constructor(e){super(e),this.rtFactoryParams=e}createService(e){return this.transcriber(e)}transcriber(e){const t=Object.assign({},e);return t.token||t.apiKey||(t.apiKey=this.rtFactoryParams.apiKey),new y(t)}createTemporaryToken(e){return t(this,void 0,void 0,(function*(){return(yield this.fetchJson("/v2/realtime/token",{method:"POST",body:JSON.stringify(e)})).token}))}}function b(e){return e.startsWith("http")||e.startsWith("https")||e.startsWith("data:")?null:e.startsWith("file://")?e.substring(7):e.startsWith("file:")?e.substring(5):e}class w extends n{constructor(e,t){super(e),this.files=t}transcribe(e,s){return t(this,void 0,void 0,(function*(){const t=yield this.submit(e);return yield this.waitUntilReady(t.id,s)}))}submit(e){return t(this,void 0,void 0,(function*(){let t,s;if("audio"in e){const{audio:i}=e,r=function(e,t){var s={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(s[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(s[i[r]]=e[i[r]])}return s}(e,["audio"]);if("string"==typeof i){const e=b(i);t=null!==e?yield this.files.upload(e):i.startsWith("data:")?yield this.files.upload(i):i}else t=yield this.files.upload(i);s=Object.assign(Object.assign({},r),{audio_url:t})}else s=e;return yield this.fetchJson("/v2/transcript",{method:"POST",body:JSON.stringify(s)})}))}create(e,s){return t(this,void 0,void 0,(function*(){var t;const i=b(e.audio_url);if(null!==i){const t=yield this.files.upload(i);e.audio_url=t}const r=yield this.fetchJson("/v2/transcript",{method:"POST",body:JSON.stringify(e)});return null===(t=null==s?void 0:s.poll)||void 0===t||t?yield this.waitUntilReady(r.id,s):r}))}waitUntilReady(e,s){return t(this,void 0,void 0,(function*(){var t,i;const r=null!==(t=null==s?void 0:s.pollingInterval)&&void 0!==t?t:3e3,n=null!==(i=null==s?void 0:s.pollingTimeout)&&void 0!==i?i:-1,o=Date.now();for(;;){const t=yield this.get(e);if("completed"===t.status||"error"===t.status)return t;if(n>0&&Date.now()-o>n)throw new Error("Polling timeout");yield new Promise((e=>setTimeout(e,r)))}}))}get(e){return this.fetchJson(`/v2/transcript/${e}`)}list(e){return t(this,void 0,void 0,(function*(){let t="/v2/transcript";"string"==typeof e?t=e:e&&(t=`${t}?${new URLSearchParams(Object.keys(e).map((t=>{var s;return[t,(null===(s=e[t])||void 0===s?void 0:s.toString())||""]})))}`);const s=yield this.fetchJson(t);for(const e of s.transcripts)e.created=new Date(e.created),e.completed&&(e.completed=new Date(e.completed));return s}))}delete(e){return this.fetchJson(`/v2/transcript/${e}`,{method:"DELETE"})}wordSearch(e,t){const s=new URLSearchParams({words:t.join(",")});return this.fetchJson(`/v2/transcript/${e}/word-search?${s.toString()}`)}sentences(e){return this.fetchJson(`/v2/transcript/${e}/sentences`)}paragraphs(e){return this.fetchJson(`/v2/transcript/${e}/paragraphs`)}subtitles(e){return t(this,arguments,void 0,(function*(e,t="srt",s){let i=`/v2/transcript/${e}/${t}`;if(s){const e=new URLSearchParams;e.set("chars_per_caption",s.toString()),i+=`?${e.toString()}`}const r=yield this.fetch(i);return yield r.text()}))}redactions(e){return this.redactedAudio(e)}redactedAudio(e){return this.fetchJson(`/v2/transcript/${e}/redacted-audio`)}redactedAudioFile(e){return t(this,void 0,void 0,(function*(){const{redacted_audio_url:t,status:s}=yield this.redactedAudio(e);if("redacted_audio_ready"!==s)throw new Error(`Redacted audio status is ${s}`);const i=yield fetch(t);if(!i.ok)throw new Error(`Failed to fetch redacted audio: ${i.statusText}`);return{arrayBuffer:i.arrayBuffer.bind(i),blob:i.blob.bind(i),body:i.body,bodyUsed:i.bodyUsed}}))}}class S extends n{upload(e){return t(this,void 0,void 0,(function*(){let s;s="string"==typeof e?e.startsWith("data:")?function(e){const t=e.split(","),s=t[0].match(/:(.*?);/)[1],i=atob(t[1]);let r=i.length;const n=new Uint8Array(r);for(;r--;)n[r]=i.charCodeAt(r);return new Blob([n],{type:s})}(e):yield function(e){return t(this,void 0,void 0,(function*(){throw new Error("Interacting with the file system is not supported in this environment.")}))}():e;return(yield this.fetchJson("/v2/upload",{method:"POST",body:s,headers:{"Content-Type":"application/octet-stream"},duplex:"half"})).upload_url}))}}const k='{"type":"Terminate"}';class T{constructor(e){if(this.listeners={},this.params=Object.assign(Object.assign({},e),{websocketBaseUrl:e.websocketBaseUrl||"wss://streaming.assemblyai.com/v3/ws"}),"token"in e&&e.token&&(this.token=e.token),"apiKey"in e&&e.apiKey&&(this.apiKey=e.apiKey),!this.token&&!this.apiKey)throw new Error("API key or temporary token is required.")}connectionUrl(){var e;const t=new URL(null!==(e=this.params.websocketBaseUrl)&&void 0!==e?e:"");if("wss:"!==t.protocol)throw new Error("Invalid protocol, must be wss");const s=new URLSearchParams;return this.token&&s.set("token",this.token),s.set("sample_rate",this.params.sampleRate.toString()),this.params.endOfTurnConfidenceThreshold&&s.set("end_of_turn_confidence_threshold",this.params.endOfTurnConfidenceThreshold.toString()),this.params.minTurnSilence?s.set("min_turn_silence",this.params.minTurnSilence.toString()):this.params.minEndOfTurnSilenceWhenConfident&&(console.warn("[Deprecation Warning] `minEndOfTurnSilenceWhenConfident` is deprecated and will be removed in a future release. Please use `minTurnSilence` instead."),s.set("min_end_of_turn_silence_when_confident",this.params.minEndOfTurnSilenceWhenConfident.toString())),this.params.maxTurnSilence&&s.set("max_turn_silence",this.params.maxTurnSilence.toString()),void 0!==this.params.vadThreshold&&s.set("vad_threshold",this.params.vadThreshold.toString()),this.params.formatTurns&&s.set("format_turns",this.params.formatTurns.toString()),this.params.encoding&&s.set("encoding",this.params.encoding.toString()),this.params.keytermsPrompt?s.set("keyterms_prompt",JSON.stringify(this.params.keytermsPrompt)):this.params.keyterms&&(console.warn("[Deprecation Warning] `keyterms` is deprecated and will be removed in a future release. Please use `keytermsPrompt` instead."),s.set("keyterms_prompt",JSON.stringify(this.params.keyterms))),this.params.prompt&&s.set("prompt",this.params.prompt),this.params.filterProfanity&&s.set("filter_profanity",this.params.filterProfanity.toString()),this.params.speechModel&&("u3-pro"===this.params.speechModel&&console.warn("[Deprecation Warning] The speech model `u3-pro` is deprecated and will be removed in a future release. Please use `u3-rt-pro` instead."),s.set("speech_model",this.params.speechModel.toString())),void 0!==this.params.languageDetection&&s.set("language_detection",this.params.languageDetection.toString()),void 0!==this.params.inactivityTimeout&&s.set("inactivity_timeout",this.params.inactivityTimeout.toString()),void 0!==this.params.speakerLabels&&s.set("speaker_labels",this.params.speakerLabels.toString()),void 0!==this.params.maxSpeakers&&s.set("max_speakers",this.params.maxSpeakers.toString()),t.search=s.toString(),t}on(e,t){this.listeners[e]=t}connect(){return new Promise((e=>{if(this.socket)throw new Error("Already connected");const t=this.connectionUrl();this.token?this.socket=h(t.toString()):(console.warn("API key authentication is not supported for the StreamingTranscriber in browser environment. Use temporary token authentication instead.\nLearn more at https://github.com/AssemblyAI/assemblyai-node-sdk/blob/main/docs/compat.md#browser-compatibility."),this.socket=h(t.toString(),{headers:{Authorization:this.apiKey}})),this.socket.binaryType="arraybuffer",this.socket.onopen=()=>{},this.socket.onclose=({code:e,reason:t})=>{var s,i;t||e in m&&(t=m[e]),null===(i=(s=this.listeners).close)||void 0===i||i.call(s,e,t)},this.socket.onerror=e=>{var t,s,i,r;e.error?null===(s=(t=this.listeners).error)||void 0===s||s.call(t,e.error):null===(r=(i=this.listeners).error)||void 0===r||r.call(i,new Error(e.message))},this.socket.onmessage=({data:t})=>{var s,i,r,n,o,a,c,l,d;const h=JSON.parse(t.toString());if("error"in h)null===(i=(s=this.listeners).error)||void 0===i||i.call(s,new f(h.error));else switch(h.type){case"Begin":e(h),null===(n=(r=this.listeners).open)||void 0===n||n.call(r,h);break;case"Turn":null===(a=(o=this.listeners).turn)||void 0===a||a.call(o,h);break;case"SpeechStarted":null===(l=(c=this.listeners).speechStarted)||void 0===l||l.call(c,h);break;case"Termination":null===(d=this.sessionTerminatedResolve)||void 0===d||d.call(this)}}}))}stream(){return new a({write:e=>{this.sendAudio(e)}})}sendAudio(e){this.send(e)}updateConfiguration(e){const t=Object.assign({type:"UpdateConfiguration"},e);this.send(JSON.stringify(t))}forceEndpoint(){this.send(JSON.stringify({type:"ForceEndpoint"}))}send(e){if(!this.socket||this.socket.readyState!==this.socket.OPEN)throw new Error("Socket is not open for communication");this.socket.send(e)}close(){return t(this,arguments,void 0,(function*(e=!0){var t;if(this.socket){if(this.socket.readyState===this.socket.OPEN)if(e){const e=new Promise((e=>{this.sessionTerminatedResolve=e}));this.socket.send(k),yield e}else this.socket.send(k);(null===(t=this.socket)||void 0===t?void 0:t.removeAllListeners)&&this.socket.removeAllListeners(),this.socket.close()}this.listeners={},this.socket=void 0}))}}class O extends n{constructor(e){super(e),this.baseServiceParams=e}transcriber(e){const t=Object.assign({},e);return t.token||t.apiKey||(t.apiKey=this.baseServiceParams.apiKey),new T(t)}createTemporaryToken(e){return t(this,void 0,void 0,(function*(){const t=new URLSearchParams;Object.entries(e).forEach((([e,s])=>{null!=s&&t.append(e,String(s))}));const s=t.toString(),i=s?`/v3/token?${s}`:"/v3/token";return(yield this.fetchJson(i,{method:"GET"})).token}))}}e.AssemblyAI=class{constructor(e){e.baseUrl=e.baseUrl||"https://api.assemblyai.com",e.baseUrl&&e.baseUrl.endsWith("/")&&(e.baseUrl=e.baseUrl.slice(0,-1)),this.files=new S(e),this.transcripts=new w(e,this.files),this.lemur=new o(e),this.realtime=new g(e),this.streaming=new O(Object.assign(Object.assign({},e),{baseUrl:e.streamingBaseUrl||"https://streaming.assemblyai.com"}))}},e.FileService=S,e.LemurService=o,e.RealtimeService=class extends y{},e.RealtimeServiceFactory=class extends g{},e.RealtimeTranscriber=y,e.RealtimeTranscriberFactory=g,e.StreamingTranscriber=T,e.TranscriptService=w}));
package/dist/browser.mjs CHANGED
@@ -15,7 +15,7 @@ if (typeof navigator !== "undefined" && navigator.userAgent) {
15
15
  defaultUserAgentString += navigator.userAgent;
16
16
  }
17
17
  const defaultUserAgent = {
18
- sdk: { name: "JavaScript", version: "4.24.0" },
18
+ sdk: { name: "JavaScript", version: "4.25.1" },
19
19
  };
20
20
  if (typeof process !== "undefined") {
21
21
  if (process.versions.node && defaultUserAgentString.indexOf("Node") === -1) {
@@ -865,6 +865,12 @@ class StreamingTranscriber {
865
865
  if (this.params.inactivityTimeout !== undefined) {
866
866
  searchParams.set("inactivity_timeout", this.params.inactivityTimeout.toString());
867
867
  }
868
+ if (this.params.speakerLabels !== undefined) {
869
+ searchParams.set("speaker_labels", this.params.speakerLabels.toString());
870
+ }
871
+ if (this.params.maxSpeakers !== undefined) {
872
+ searchParams.set("max_speakers", this.params.maxSpeakers.toString());
873
+ }
868
874
  url.search = searchParams.toString();
869
875
  return url;
870
876
  }
@@ -922,6 +928,10 @@ Learn more at https://github.com/AssemblyAI/assemblyai-node-sdk/blob/main/docs/c
922
928
  this.listeners.turn?.(message);
923
929
  break;
924
930
  }
931
+ case "SpeechStarted": {
932
+ this.listeners.speechStarted?.(message);
933
+ break;
934
+ }
925
935
  case "Termination": {
926
936
  this.sessionTerminatedResolve?.();
927
937
  break;
package/dist/bun.mjs CHANGED
@@ -17,7 +17,7 @@ if (typeof navigator !== "undefined" && navigator.userAgent) {
17
17
  defaultUserAgentString += navigator.userAgent;
18
18
  }
19
19
  const defaultUserAgent = {
20
- sdk: { name: "JavaScript", version: "4.24.0" },
20
+ sdk: { name: "JavaScript", version: "4.25.1" },
21
21
  };
22
22
  if (typeof process !== "undefined") {
23
23
  if (process.versions.node && defaultUserAgentString.indexOf("Node") === -1) {
@@ -846,6 +846,12 @@ class StreamingTranscriber {
846
846
  if (this.params.inactivityTimeout !== undefined) {
847
847
  searchParams.set("inactivity_timeout", this.params.inactivityTimeout.toString());
848
848
  }
849
+ if (this.params.speakerLabels !== undefined) {
850
+ searchParams.set("speaker_labels", this.params.speakerLabels.toString());
851
+ }
852
+ if (this.params.maxSpeakers !== undefined) {
853
+ searchParams.set("max_speakers", this.params.maxSpeakers.toString());
854
+ }
849
855
  url.search = searchParams.toString();
850
856
  return url;
851
857
  }
@@ -899,6 +905,10 @@ class StreamingTranscriber {
899
905
  this.listeners.turn?.(message);
900
906
  break;
901
907
  }
908
+ case "SpeechStarted": {
909
+ this.listeners.speechStarted?.(message);
910
+ break;
911
+ }
902
912
  case "Termination": {
903
913
  this.sessionTerminatedResolve?.();
904
914
  break;
package/dist/deno.mjs CHANGED
@@ -17,7 +17,7 @@ if (typeof navigator !== "undefined" && navigator.userAgent) {
17
17
  defaultUserAgentString += navigator.userAgent;
18
18
  }
19
19
  const defaultUserAgent = {
20
- sdk: { name: "JavaScript", version: "4.24.0" },
20
+ sdk: { name: "JavaScript", version: "4.25.1" },
21
21
  };
22
22
  if (typeof process !== "undefined") {
23
23
  if (process.versions.node && defaultUserAgentString.indexOf("Node") === -1) {
@@ -846,6 +846,12 @@ class StreamingTranscriber {
846
846
  if (this.params.inactivityTimeout !== undefined) {
847
847
  searchParams.set("inactivity_timeout", this.params.inactivityTimeout.toString());
848
848
  }
849
+ if (this.params.speakerLabels !== undefined) {
850
+ searchParams.set("speaker_labels", this.params.speakerLabels.toString());
851
+ }
852
+ if (this.params.maxSpeakers !== undefined) {
853
+ searchParams.set("max_speakers", this.params.maxSpeakers.toString());
854
+ }
849
855
  url.search = searchParams.toString();
850
856
  return url;
851
857
  }
@@ -899,6 +905,10 @@ class StreamingTranscriber {
899
905
  this.listeners.turn?.(message);
900
906
  break;
901
907
  }
908
+ case "SpeechStarted": {
909
+ this.listeners.speechStarted?.(message);
910
+ break;
911
+ }
902
912
  case "Termination": {
903
913
  this.sessionTerminatedResolve?.();
904
914
  break;
package/dist/index.cjs CHANGED
@@ -63,7 +63,7 @@ if (typeof navigator !== "undefined" && navigator.userAgent) {
63
63
  defaultUserAgentString += navigator.userAgent;
64
64
  }
65
65
  const defaultUserAgent = {
66
- sdk: { name: "JavaScript", version: "4.24.0" },
66
+ sdk: { name: "JavaScript", version: "4.25.1" },
67
67
  };
68
68
  if (typeof process !== "undefined") {
69
69
  if (process.versions.node && defaultUserAgentString.indexOf("Node") === -1) {
@@ -937,6 +937,12 @@ class StreamingTranscriber {
937
937
  if (this.params.inactivityTimeout !== undefined) {
938
938
  searchParams.set("inactivity_timeout", this.params.inactivityTimeout.toString());
939
939
  }
940
+ if (this.params.speakerLabels !== undefined) {
941
+ searchParams.set("speaker_labels", this.params.speakerLabels.toString());
942
+ }
943
+ if (this.params.maxSpeakers !== undefined) {
944
+ searchParams.set("max_speakers", this.params.maxSpeakers.toString());
945
+ }
940
946
  url.search = searchParams.toString();
941
947
  return url;
942
948
  }
@@ -977,7 +983,7 @@ class StreamingTranscriber {
977
983
  (_d = (_c = this.listeners).error) === null || _d === void 0 ? void 0 : _d.call(_c, new Error(event.message));
978
984
  };
979
985
  this.socket.onmessage = ({ data }) => {
980
- var _a, _b, _c, _d, _e, _f, _g;
986
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j;
981
987
  const message = JSON.parse(data.toString());
982
988
  if ("error" in message) {
983
989
  (_b = (_a = this.listeners).error) === null || _b === void 0 ? void 0 : _b.call(_a, new StreamingError(message.error));
@@ -993,8 +999,12 @@ class StreamingTranscriber {
993
999
  (_f = (_e = this.listeners).turn) === null || _f === void 0 ? void 0 : _f.call(_e, message);
994
1000
  break;
995
1001
  }
1002
+ case "SpeechStarted": {
1003
+ (_h = (_g = this.listeners).speechStarted) === null || _h === void 0 ? void 0 : _h.call(_g, message);
1004
+ break;
1005
+ }
996
1006
  case "Termination": {
997
- (_g = this.sessionTerminatedResolve) === null || _g === void 0 ? void 0 : _g.call(this);
1007
+ (_j = this.sessionTerminatedResolve) === null || _j === void 0 ? void 0 : _j.call(this);
998
1008
  break;
999
1009
  }
1000
1010
  }
package/dist/index.mjs CHANGED
@@ -61,7 +61,7 @@ if (typeof navigator !== "undefined" && navigator.userAgent) {
61
61
  defaultUserAgentString += navigator.userAgent;
62
62
  }
63
63
  const defaultUserAgent = {
64
- sdk: { name: "JavaScript", version: "4.24.0" },
64
+ sdk: { name: "JavaScript", version: "4.25.1" },
65
65
  };
66
66
  if (typeof process !== "undefined") {
67
67
  if (process.versions.node && defaultUserAgentString.indexOf("Node") === -1) {
@@ -935,6 +935,12 @@ class StreamingTranscriber {
935
935
  if (this.params.inactivityTimeout !== undefined) {
936
936
  searchParams.set("inactivity_timeout", this.params.inactivityTimeout.toString());
937
937
  }
938
+ if (this.params.speakerLabels !== undefined) {
939
+ searchParams.set("speaker_labels", this.params.speakerLabels.toString());
940
+ }
941
+ if (this.params.maxSpeakers !== undefined) {
942
+ searchParams.set("max_speakers", this.params.maxSpeakers.toString());
943
+ }
938
944
  url.search = searchParams.toString();
939
945
  return url;
940
946
  }
@@ -975,7 +981,7 @@ class StreamingTranscriber {
975
981
  (_d = (_c = this.listeners).error) === null || _d === void 0 ? void 0 : _d.call(_c, new Error(event.message));
976
982
  };
977
983
  this.socket.onmessage = ({ data }) => {
978
- var _a, _b, _c, _d, _e, _f, _g;
984
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j;
979
985
  const message = JSON.parse(data.toString());
980
986
  if ("error" in message) {
981
987
  (_b = (_a = this.listeners).error) === null || _b === void 0 ? void 0 : _b.call(_a, new StreamingError(message.error));
@@ -991,8 +997,12 @@ class StreamingTranscriber {
991
997
  (_f = (_e = this.listeners).turn) === null || _f === void 0 ? void 0 : _f.call(_e, message);
992
998
  break;
993
999
  }
1000
+ case "SpeechStarted": {
1001
+ (_h = (_g = this.listeners).speechStarted) === null || _h === void 0 ? void 0 : _h.call(_g, message);
1002
+ break;
1003
+ }
994
1004
  case "Termination": {
995
- (_g = this.sessionTerminatedResolve) === null || _g === void 0 ? void 0 : _g.call(this);
1005
+ (_j = this.sessionTerminatedResolve) === null || _j === void 0 ? void 0 : _j.call(this);
996
1006
  break;
997
1007
  }
998
1008
  }
package/dist/node.cjs CHANGED
@@ -22,7 +22,7 @@ if (typeof navigator !== "undefined" && navigator.userAgent) {
22
22
  defaultUserAgentString += navigator.userAgent;
23
23
  }
24
24
  const defaultUserAgent = {
25
- sdk: { name: "JavaScript", version: "4.24.0" },
25
+ sdk: { name: "JavaScript", version: "4.25.1" },
26
26
  };
27
27
  if (typeof process !== "undefined") {
28
28
  if (process.versions.node && defaultUserAgentString.indexOf("Node") === -1) {
@@ -845,6 +845,12 @@ class StreamingTranscriber {
845
845
  if (this.params.inactivityTimeout !== undefined) {
846
846
  searchParams.set("inactivity_timeout", this.params.inactivityTimeout.toString());
847
847
  }
848
+ if (this.params.speakerLabels !== undefined) {
849
+ searchParams.set("speaker_labels", this.params.speakerLabels.toString());
850
+ }
851
+ if (this.params.maxSpeakers !== undefined) {
852
+ searchParams.set("max_speakers", this.params.maxSpeakers.toString());
853
+ }
848
854
  url.search = searchParams.toString();
849
855
  return url;
850
856
  }
@@ -898,6 +904,10 @@ class StreamingTranscriber {
898
904
  this.listeners.turn?.(message);
899
905
  break;
900
906
  }
907
+ case "SpeechStarted": {
908
+ this.listeners.speechStarted?.(message);
909
+ break;
910
+ }
901
911
  case "Termination": {
902
912
  this.sessionTerminatedResolve?.();
903
913
  break;
package/dist/node.mjs CHANGED
@@ -20,7 +20,7 @@ if (typeof navigator !== "undefined" && navigator.userAgent) {
20
20
  defaultUserAgentString += navigator.userAgent;
21
21
  }
22
22
  const defaultUserAgent = {
23
- sdk: { name: "JavaScript", version: "4.24.0" },
23
+ sdk: { name: "JavaScript", version: "4.25.1" },
24
24
  };
25
25
  if (typeof process !== "undefined") {
26
26
  if (process.versions.node && defaultUserAgentString.indexOf("Node") === -1) {
@@ -843,6 +843,12 @@ class StreamingTranscriber {
843
843
  if (this.params.inactivityTimeout !== undefined) {
844
844
  searchParams.set("inactivity_timeout", this.params.inactivityTimeout.toString());
845
845
  }
846
+ if (this.params.speakerLabels !== undefined) {
847
+ searchParams.set("speaker_labels", this.params.speakerLabels.toString());
848
+ }
849
+ if (this.params.maxSpeakers !== undefined) {
850
+ searchParams.set("max_speakers", this.params.maxSpeakers.toString());
851
+ }
846
852
  url.search = searchParams.toString();
847
853
  return url;
848
854
  }
@@ -896,6 +902,10 @@ class StreamingTranscriber {
896
902
  this.listeners.turn?.(message);
897
903
  break;
898
904
  }
905
+ case "SpeechStarted": {
906
+ this.listeners.speechStarted?.(message);
907
+ break;
908
+ }
899
909
  case "Termination": {
900
910
  this.sessionTerminatedResolve?.();
901
911
  break;
@@ -21,15 +21,18 @@ export type StreamingTranscriberParams = {
21
21
  speechModel?: StreamingSpeechModel;
22
22
  languageDetection?: boolean;
23
23
  inactivityTimeout?: number;
24
+ speakerLabels?: boolean;
25
+ maxSpeakers?: number;
24
26
  };
25
- export type StreamingEvents = "open" | "close" | "turn" | "error";
27
+ export type StreamingEvents = "open" | "close" | "turn" | "speechStarted" | "error";
26
28
  export type StreamingListeners = {
27
29
  open?: (event: BeginEvent) => void;
28
30
  close?: (code: number, reason: string) => void;
29
31
  turn?: (event: TurnEvent) => void;
32
+ speechStarted?: (event: SpeechStartedEvent) => void;
30
33
  error?: (error: Error) => void;
31
34
  };
32
- export type StreamingSpeechModel = "universal-streaming-english" | "universal-streaming-multilingual" | "u3-rt-pro" | "u3-pro";
35
+ export type StreamingSpeechModel = "universal-streaming-english" | "universal-streaming-multilingual" | "u3-rt-pro" | "whisper-rt" | "u3-pro";
33
36
  export type StreamingTokenParams = {
34
37
  expires_in_seconds: number;
35
38
  max_session_duration_seconds?: number;
@@ -43,6 +46,10 @@ export type BeginEvent = {
43
46
  id: string;
44
47
  expires_at: number;
45
48
  };
49
+ export type SpeechStartedEvent = {
50
+ type: "SpeechStarted";
51
+ timestamp: number;
52
+ };
46
53
  export type TurnEvent = {
47
54
  type: "Turn";
48
55
  turn_order: number;
@@ -53,6 +60,7 @@ export type TurnEvent = {
53
60
  words: StreamingWord[];
54
61
  language_code?: string;
55
62
  language_confidence?: number;
63
+ speaker_label?: string;
56
64
  };
57
65
  export type StreamingWord = {
58
66
  start: number;
@@ -90,5 +98,5 @@ export type StreamingForceEndpoint = {
90
98
  export type ErrorEvent = {
91
99
  error: string;
92
100
  };
93
- export type StreamingEventMessage = BeginEvent | TurnEvent | TerminationEvent | ErrorEvent;
101
+ export type StreamingEventMessage = BeginEvent | TurnEvent | SpeechStartedEvent | TerminationEvent | ErrorEvent;
94
102
  export type StreamingOperationMessage = StreamingUpdateConfiguration | StreamingForceEndpoint | StreamingTerminateSession;
package/dist/workerd.mjs CHANGED
@@ -15,7 +15,7 @@ if (typeof navigator !== "undefined" && navigator.userAgent) {
15
15
  defaultUserAgentString += navigator.userAgent;
16
16
  }
17
17
  const defaultUserAgent = {
18
- sdk: { name: "JavaScript", version: "4.24.0" },
18
+ sdk: { name: "JavaScript", version: "4.25.1" },
19
19
  };
20
20
  if (typeof process !== "undefined") {
21
21
  if (process.versions.node && defaultUserAgentString.indexOf("Node") === -1) {
@@ -848,6 +848,12 @@ class StreamingTranscriber {
848
848
  if (this.params.inactivityTimeout !== undefined) {
849
849
  searchParams.set("inactivity_timeout", this.params.inactivityTimeout.toString());
850
850
  }
851
+ if (this.params.speakerLabels !== undefined) {
852
+ searchParams.set("speaker_labels", this.params.speakerLabels.toString());
853
+ }
854
+ if (this.params.maxSpeakers !== undefined) {
855
+ searchParams.set("max_speakers", this.params.maxSpeakers.toString());
856
+ }
851
857
  url.search = searchParams.toString();
852
858
  return url;
853
859
  }
@@ -901,6 +907,10 @@ class StreamingTranscriber {
901
907
  this.listeners.turn?.(message);
902
908
  break;
903
909
  }
910
+ case "SpeechStarted": {
911
+ this.listeners.speechStarted?.(message);
912
+ break;
913
+ }
904
914
  case "Termination": {
905
915
  this.sessionTerminatedResolve?.();
906
916
  break;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "assemblyai",
3
- "version": "4.24.0",
3
+ "version": "4.25.1",
4
4
  "description": "The AssemblyAI JavaScript SDK provides an easy-to-use interface for interacting with the AssemblyAI API, which supports async and real-time transcription, as well as the latest LeMUR models.",
5
5
  "engines": {
6
6
  "node": ">=18"
@@ -165,6 +165,14 @@ export class StreamingTranscriber {
165
165
  );
166
166
  }
167
167
 
168
+ if (this.params.speakerLabels !== undefined) {
169
+ searchParams.set("speaker_labels", this.params.speakerLabels.toString());
170
+ }
171
+
172
+ if (this.params.maxSpeakers !== undefined) {
173
+ searchParams.set("max_speakers", this.params.maxSpeakers.toString());
174
+ }
175
+
168
176
  url.search = searchParams.toString();
169
177
 
170
178
  return url;
@@ -238,6 +246,10 @@ Learn more at https://github.com/AssemblyAI/assemblyai-node-sdk/blob/main/docs/c
238
246
  this.listeners.turn?.(message);
239
247
  break;
240
248
  }
249
+ case "SpeechStarted": {
250
+ this.listeners.speechStarted?.(message);
251
+ break;
252
+ }
241
253
  case "Termination": {
242
254
  this.sessionTerminatedResolve?.();
243
255
  break;
@@ -22,14 +22,22 @@ export type StreamingTranscriberParams = {
22
22
  speechModel?: StreamingSpeechModel;
23
23
  languageDetection?: boolean;
24
24
  inactivityTimeout?: number;
25
+ speakerLabels?: boolean;
26
+ maxSpeakers?: number;
25
27
  };
26
28
 
27
- export type StreamingEvents = "open" | "close" | "turn" | "error";
29
+ export type StreamingEvents =
30
+ | "open"
31
+ | "close"
32
+ | "turn"
33
+ | "speechStarted"
34
+ | "error";
28
35
 
29
36
  export type StreamingListeners = {
30
37
  open?: (event: BeginEvent) => void;
31
38
  close?: (code: number, reason: string) => void;
32
39
  turn?: (event: TurnEvent) => void;
40
+ speechStarted?: (event: SpeechStartedEvent) => void;
33
41
  error?: (error: Error) => void;
34
42
  };
35
43
 
@@ -37,6 +45,7 @@ export type StreamingSpeechModel =
37
45
  | "universal-streaming-english"
38
46
  | "universal-streaming-multilingual"
39
47
  | "u3-rt-pro"
48
+ | "whisper-rt"
40
49
  | "u3-pro";
41
50
 
42
51
  export type StreamingTokenParams = {
@@ -56,6 +65,11 @@ export type BeginEvent = {
56
65
  expires_at: number;
57
66
  };
58
67
 
68
+ export type SpeechStartedEvent = {
69
+ type: "SpeechStarted";
70
+ timestamp: number;
71
+ };
72
+
59
73
  export type TurnEvent = {
60
74
  type: "Turn";
61
75
  turn_order: number;
@@ -66,6 +80,7 @@ export type TurnEvent = {
66
80
  words: StreamingWord[];
67
81
  language_code?: string;
68
82
  language_confidence?: number;
83
+ speaker_label?: string;
69
84
  };
70
85
 
71
86
  export type StreamingWord = {
@@ -113,6 +128,7 @@ export type ErrorEvent = {
113
128
  export type StreamingEventMessage =
114
129
  | BeginEvent
115
130
  | TurnEvent
131
+ | SpeechStartedEvent
116
132
  | TerminationEvent
117
133
  | ErrorEvent;
118
134