assemblyai 4.5.0 → 4.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,12 @@
1
1
  # Changelog
2
2
 
3
+ ## [4.6.0]
4
+
5
+ - Add more TSDoc comments for `RealtimeService` documentation
6
+ - Add new LeMUR models
7
+ - Add `TranscriptWebhookNotification` which is a union of `TranscriptReadyNotification` or `RedactedAudioNotification`
8
+ - Add `RedactedAudioNotification` which represents the body of the PII redacted audio webhook notification.
9
+
3
10
  ## [4.5.0]
4
11
 
5
12
  - You can now retrieve previous LeMUR responses using `client.lemur.getResponse<LemurTask>("YOUR_REQUEST_ID")`.
@@ -95,7 +95,14 @@
95
95
  const defaultRealtimeUrl = "wss://api.assemblyai.com/v2/realtime/ws";
96
96
  const forceEndOfUtteranceMessage = `{"force_end_utterance":true}`;
97
97
  const terminateSessionMessage = `{"terminate_session":true}`;
98
+ /**
99
+ * RealtimeTranscriber connects to the Streaming Speech-to-Text API and lets you transcribe audio in real-time.
100
+ */
98
101
  class RealtimeTranscriber {
102
+ /**
103
+ * Create a new RealtimeTranscriber.
104
+ * @param params - Parameters to configure the RealtimeTranscriber
105
+ */
99
106
  constructor(params) {
100
107
  var _a, _b;
101
108
  this.listeners = {};
@@ -136,10 +143,19 @@
136
143
  url.search = searchParams.toString();
137
144
  return url;
138
145
  }
146
+ /**
147
+ * Add a listener for an event.
148
+ * @param event - The event to listen for.
149
+ * @param listener - The function to call when the event is emitted.
150
+ */
139
151
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
140
152
  on(event, listener) {
141
153
  this.listeners[event] = listener;
142
154
  }
155
+ /**
156
+ * Connect to the server and begin a new session.
157
+ * @returns A promise that resolves when the connection is established and the session begins.
158
+ */
143
159
  connect() {
144
160
  return new Promise((resolve) => {
145
161
  if (this.socket) {
@@ -221,9 +237,17 @@
221
237
  };
222
238
  });
223
239
  }
240
+ /**
241
+ * Send audio data to the server.
242
+ * @param audio - The audio data to send to the server.
243
+ */
224
244
  sendAudio(audio) {
225
245
  this.send(audio);
226
246
  }
247
+ /**
248
+ * Create a writable stream that can be used to send audio data to the server.
249
+ * @returns A writable stream that can be used to send audio data to the server.
250
+ */
227
251
  stream() {
228
252
  return new WritableStream({
229
253
  write: (chunk) => {
@@ -251,6 +275,11 @@
251
275
  }
252
276
  this.socket.send(data);
253
277
  }
278
+ /**
279
+ * Close the connection to the server.
280
+ * @param waitForSessionTermination - If true, the method will wait for the session to be terminated before closing the connection.
281
+ * While waiting for the session to be terminated, you will receive the final transcript and session information.
282
+ */
254
283
  close() {
255
284
  return __awaiter(this, arguments, void 0, function* (waitForSessionTermination = true) {
256
285
  var _a;
@@ -65,7 +65,7 @@
65
65
  defaultUserAgentString += navigator.userAgent;
66
66
  }
67
67
  const defaultUserAgent = {
68
- sdk: { name: "JavaScript", version: "4.5.0" },
68
+ sdk: { name: "JavaScript", version: "4.6.0" },
69
69
  };
70
70
  if (typeof process !== "undefined") {
71
71
  if (process.versions.node && defaultUserAgentString.indexOf("Node") === -1) {
@@ -252,7 +252,14 @@
252
252
  const defaultRealtimeUrl = "wss://api.assemblyai.com/v2/realtime/ws";
253
253
  const forceEndOfUtteranceMessage = `{"force_end_utterance":true}`;
254
254
  const terminateSessionMessage = `{"terminate_session":true}`;
255
+ /**
256
+ * RealtimeTranscriber connects to the Streaming Speech-to-Text API and lets you transcribe audio in real-time.
257
+ */
255
258
  class RealtimeTranscriber {
259
+ /**
260
+ * Create a new RealtimeTranscriber.
261
+ * @param params - Parameters to configure the RealtimeTranscriber
262
+ */
256
263
  constructor(params) {
257
264
  var _a, _b;
258
265
  this.listeners = {};
@@ -293,10 +300,19 @@
293
300
  url.search = searchParams.toString();
294
301
  return url;
295
302
  }
303
+ /**
304
+ * Add a listener for an event.
305
+ * @param event - The event to listen for.
306
+ * @param listener - The function to call when the event is emitted.
307
+ */
296
308
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
297
309
  on(event, listener) {
298
310
  this.listeners[event] = listener;
299
311
  }
312
+ /**
313
+ * Connect to the server and begin a new session.
314
+ * @returns A promise that resolves when the connection is established and the session begins.
315
+ */
300
316
  connect() {
301
317
  return new Promise((resolve) => {
302
318
  if (this.socket) {
@@ -378,9 +394,17 @@
378
394
  };
379
395
  });
380
396
  }
397
+ /**
398
+ * Send audio data to the server.
399
+ * @param audio - The audio data to send to the server.
400
+ */
381
401
  sendAudio(audio) {
382
402
  this.send(audio);
383
403
  }
404
+ /**
405
+ * Create a writable stream that can be used to send audio data to the server.
406
+ * @returns A writable stream that can be used to send audio data to the server.
407
+ */
384
408
  stream() {
385
409
  return new WritableStream({
386
410
  write: (chunk) => {
@@ -408,6 +432,11 @@
408
432
  }
409
433
  this.socket.send(data);
410
434
  }
435
+ /**
436
+ * Close the connection to the server.
437
+ * @param waitForSessionTermination - If true, the method will wait for the session to be terminated before closing the connection.
438
+ * While waiting for the session to be terminated, you will receive the final transcript and session information.
439
+ */
411
440
  close() {
412
441
  return __awaiter(this, arguments, void 0, function* (waitForSessionTermination = true) {
413
442
  var _a;
@@ -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,o){function r(e){try{c(i.next(e))}catch(e){o(e)}}function a(e){try{c(i.throw(e))}catch(e){o(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(r,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.5.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 o{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 r extends o{summary(e){return this.fetchJson("/lemur/v3/generate/summary",{method:"POST",body:JSON.stringify(e)})}questionAnswer(e){return this.fetchJson("/lemur/v3/generate/question-answer",{method:"POST",body:JSON.stringify(e)})}actionItems(e){return this.fetchJson("/lemur/v3/generate/action-items",{method:"POST",body:JSON.stringify(e)})}task(e){return this.fetchJson("/lemur/v3/generate/task",{method:"POST",body:JSON.stringify(e)})}getResponse(e){return this.fetchJson(`/lemur/v3/${e}`)}purgeRequestData(e){return this.fetchJson(`/lemur/v3/${e}`,{method:"DELETE"})}}const{WritableStream:a}="undefined"!=typeof window?window:"undefined"!=typeof global?global:globalThis;var c,d;const l=null!==(d=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!==d?d:null===self||void 0===self?void 0:self.WebSocket,u=(e,t)=>t?new l(e,t):new l(e);var h;!function(e){e[e.BadSampleRate=4e3]="BadSampleRate",e[e.AuthFailed=4001]="AuthFailed",e[e.InsufficientFundsOrFreeAccount=4002]="InsufficientFundsOrFreeAccount",e[e.NonexistentSessionId=4004]="NonexistentSessionId",e[e.SessionExpired=4008]="SessionExpired",e[e.ClosedSession=4010]="ClosedSession",e[e.RateLimited=4029]="RateLimited",e[e.UniqueSessionViolation=4030]="UniqueSessionViolation",e[e.SessionTimeout=4031]="SessionTimeout",e[e.AudioTooShort=4032]="AudioTooShort",e[e.AudioTooLong=4033]="AudioTooLong",e[e.BadJson=4100]="BadJson",e[e.BadSchema=4101]="BadSchema",e[e.TooManyStreams=4102]="TooManyStreams",e[e.Reconnected=4103]="Reconnected",e[e.ReconnectAttemptsExhausted=1013]="ReconnectAttemptsExhausted"}(h||(h={}));const f={[h.BadSampleRate]:"Sample rate must be a positive integer",[h.AuthFailed]:"Not Authorized",[h.InsufficientFundsOrFreeAccount]:"Insufficient funds or you are using a free account. This feature is paid-only and requires you to add a credit card. Please visit https://assemblyai.com/dashboard/ to add a credit card to your account.",[h.NonexistentSessionId]:"Session ID does not exist",[h.SessionExpired]:"Session has expired",[h.ClosedSession]:"Session is closed",[h.RateLimited]:"Rate limited",[h.UniqueSessionViolation]:"Unique session violation",[h.SessionTimeout]:"Session Timeout",[h.AudioTooShort]:"Audio too short",[h.AudioTooLong]:"Audio too long",[h.BadJson]:"Bad JSON",[h.BadSchema]:"Bad schema",[h.TooManyStreams]:"Too many streams",[h.Reconnected]:"Reconnected",[h.ReconnectAttemptsExhausted]:"Reconnect attempts exhausted"};class p extends Error{}const m='{"terminate_session":true}';class v{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=u(t.toString()):this.socket=u(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 h&&(t=f[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,o,r,a,c,d,l,u,h,f,m,v,y;const b=JSON.parse(t.toString());if("error"in b)null===(i=(s=this.listeners).error)||void 0===i||i.call(s,new p(b.error));else switch(b.message_type){case"SessionBegins":{const t={sessionId:b.session_id,expiresAt:new Date(b.expires_at)};e(t),null===(o=(n=this.listeners).open)||void 0===o||o.call(n,t);break}case"PartialTranscript":b.created=new Date(b.created),null===(a=(r=this.listeners).transcript)||void 0===a||a.call(r,b),null===(d=(c=this.listeners)["transcript.partial"])||void 0===d||d.call(c,b);break;case"FinalTranscript":b.created=new Date(b.created),null===(u=(l=this.listeners).transcript)||void 0===u||u.call(l,b),null===(f=(h=this.listeners)["transcript.final"])||void 0===f||f.call(h,b);break;case"SessionInformation":null===(v=(m=this.listeners).session_information)||void 0===v||v.call(m,b);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(m),yield e}else this.socket.send(m);(null===(t=this.socket)||void 0===t?void 0:t.removeAllListeners)&&this.socket.removeAllListeners(),this.socket.close()}this.listeners={},this.socket=void 0}))}}class y extends o{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 v(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 S extends o{constructor(e,t){super(e),this.files=t}transcribe(e,s){return t(this,void 0,void 0,(function*(){g(e);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(g(e),"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;g(e);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,o=null!==(i=null==s?void 0:s.pollingTimeout)&&void 0!==i?i:-1,r=Date.now();for(;;){const t=yield this.get(e);if("completed"===t.status||"error"===t.status)return t;if(o>0&&Date.now()-r>o)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}}))}}function g(e){e&&"conformer-2"===e.speech_model&&console.warn("The speech_model conformer-2 option is deprecated and will stop working in the near future. Use best or nano instead.")}class w extends o{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 o=new Uint8Array(n);for(;n--;)o[n]=i.charCodeAt(n);return new Blob([o],{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}))}}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 w(e),this.transcripts=new S(e,this.files),this.lemur=new r(e),this.realtime=new y(e)}},e.FileService=w,e.LemurService=r,e.RealtimeService=class extends v{},e.RealtimeServiceFactory=class extends y{},e.RealtimeTranscriber=v,e.RealtimeTranscriberFactory=y,e.TranscriptService=S}));
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,o){function r(e){try{c(i.next(e))}catch(e){o(e)}}function a(e){try{c(i.throw(e))}catch(e){o(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(r,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.6.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 o{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 r extends o{summary(e){return this.fetchJson("/lemur/v3/generate/summary",{method:"POST",body:JSON.stringify(e)})}questionAnswer(e){return this.fetchJson("/lemur/v3/generate/question-answer",{method:"POST",body:JSON.stringify(e)})}actionItems(e){return this.fetchJson("/lemur/v3/generate/action-items",{method:"POST",body:JSON.stringify(e)})}task(e){return this.fetchJson("/lemur/v3/generate/task",{method:"POST",body:JSON.stringify(e)})}getResponse(e){return this.fetchJson(`/lemur/v3/${e}`)}purgeRequestData(e){return this.fetchJson(`/lemur/v3/${e}`,{method:"DELETE"})}}const{WritableStream:a}="undefined"!=typeof window?window:"undefined"!=typeof global?global:globalThis;var c,d;const l=null!==(d=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!==d?d:null===self||void 0===self?void 0:self.WebSocket,u=(e,t)=>t?new l(e,t):new l(e);var h;!function(e){e[e.BadSampleRate=4e3]="BadSampleRate",e[e.AuthFailed=4001]="AuthFailed",e[e.InsufficientFundsOrFreeAccount=4002]="InsufficientFundsOrFreeAccount",e[e.NonexistentSessionId=4004]="NonexistentSessionId",e[e.SessionExpired=4008]="SessionExpired",e[e.ClosedSession=4010]="ClosedSession",e[e.RateLimited=4029]="RateLimited",e[e.UniqueSessionViolation=4030]="UniqueSessionViolation",e[e.SessionTimeout=4031]="SessionTimeout",e[e.AudioTooShort=4032]="AudioTooShort",e[e.AudioTooLong=4033]="AudioTooLong",e[e.BadJson=4100]="BadJson",e[e.BadSchema=4101]="BadSchema",e[e.TooManyStreams=4102]="TooManyStreams",e[e.Reconnected=4103]="Reconnected",e[e.ReconnectAttemptsExhausted=1013]="ReconnectAttemptsExhausted"}(h||(h={}));const f={[h.BadSampleRate]:"Sample rate must be a positive integer",[h.AuthFailed]:"Not Authorized",[h.InsufficientFundsOrFreeAccount]:"Insufficient funds or you are using a free account. This feature is paid-only and requires you to add a credit card. Please visit https://assemblyai.com/dashboard/ to add a credit card to your account.",[h.NonexistentSessionId]:"Session ID does not exist",[h.SessionExpired]:"Session has expired",[h.ClosedSession]:"Session is closed",[h.RateLimited]:"Rate limited",[h.UniqueSessionViolation]:"Unique session violation",[h.SessionTimeout]:"Session Timeout",[h.AudioTooShort]:"Audio too short",[h.AudioTooLong]:"Audio too long",[h.BadJson]:"Bad JSON",[h.BadSchema]:"Bad schema",[h.TooManyStreams]:"Too many streams",[h.Reconnected]:"Reconnected",[h.ReconnectAttemptsExhausted]:"Reconnect attempts exhausted"};class p extends Error{}const m='{"terminate_session":true}';class v{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=u(t.toString()):this.socket=u(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 h&&(t=f[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,o,r,a,c,d,l,u,h,f,m,v,y;const b=JSON.parse(t.toString());if("error"in b)null===(i=(s=this.listeners).error)||void 0===i||i.call(s,new p(b.error));else switch(b.message_type){case"SessionBegins":{const t={sessionId:b.session_id,expiresAt:new Date(b.expires_at)};e(t),null===(o=(n=this.listeners).open)||void 0===o||o.call(n,t);break}case"PartialTranscript":b.created=new Date(b.created),null===(a=(r=this.listeners).transcript)||void 0===a||a.call(r,b),null===(d=(c=this.listeners)["transcript.partial"])||void 0===d||d.call(c,b);break;case"FinalTranscript":b.created=new Date(b.created),null===(u=(l=this.listeners).transcript)||void 0===u||u.call(l,b),null===(f=(h=this.listeners)["transcript.final"])||void 0===f||f.call(h,b);break;case"SessionInformation":null===(v=(m=this.listeners).session_information)||void 0===v||v.call(m,b);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(m),yield e}else this.socket.send(m);(null===(t=this.socket)||void 0===t?void 0:t.removeAllListeners)&&this.socket.removeAllListeners(),this.socket.close()}this.listeners={},this.socket=void 0}))}}class y extends o{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 v(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 S extends o{constructor(e,t){super(e),this.files=t}transcribe(e,s){return t(this,void 0,void 0,(function*(){g(e);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(g(e),"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;g(e);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,o=null!==(i=null==s?void 0:s.pollingTimeout)&&void 0!==i?i:-1,r=Date.now();for(;;){const t=yield this.get(e);if("completed"===t.status||"error"===t.status)return t;if(o>0&&Date.now()-r>o)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}}))}}function g(e){e&&"conformer-2"===e.speech_model&&console.warn("The speech_model conformer-2 option is deprecated and will stop working in the near future. Use best or nano instead.")}class w extends o{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 o=new Uint8Array(n);for(;n--;)o[n]=i.charCodeAt(n);return new Blob([o],{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}))}}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 w(e),this.transcripts=new S(e,this.files),this.lemur=new r(e),this.realtime=new y(e)}},e.FileService=w,e.LemurService=r,e.RealtimeService=class extends v{},e.RealtimeServiceFactory=class extends y{},e.RealtimeTranscriber=v,e.RealtimeTranscriberFactory=y,e.TranscriptService=S}));
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.5.0" },
18
+ sdk: { name: "JavaScript", version: "4.6.0" },
19
19
  };
20
20
  if (typeof process !== "undefined") {
21
21
  if (process.versions.node && defaultUserAgentString.indexOf("Node") === -1) {
@@ -197,7 +197,14 @@ class RealtimeError extends Error {
197
197
  const defaultRealtimeUrl = "wss://api.assemblyai.com/v2/realtime/ws";
198
198
  const forceEndOfUtteranceMessage = `{"force_end_utterance":true}`;
199
199
  const terminateSessionMessage = `{"terminate_session":true}`;
200
+ /**
201
+ * RealtimeTranscriber connects to the Streaming Speech-to-Text API and lets you transcribe audio in real-time.
202
+ */
200
203
  class RealtimeTranscriber {
204
+ /**
205
+ * Create a new RealtimeTranscriber.
206
+ * @param params - Parameters to configure the RealtimeTranscriber
207
+ */
201
208
  constructor(params) {
202
209
  this.listeners = {};
203
210
  this.realtimeUrl = params.realtimeUrl ?? defaultRealtimeUrl;
@@ -237,10 +244,19 @@ class RealtimeTranscriber {
237
244
  url.search = searchParams.toString();
238
245
  return url;
239
246
  }
247
+ /**
248
+ * Add a listener for an event.
249
+ * @param event - The event to listen for.
250
+ * @param listener - The function to call when the event is emitted.
251
+ */
240
252
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
241
253
  on(event, listener) {
242
254
  this.listeners[event] = listener;
243
255
  }
256
+ /**
257
+ * Connect to the server and begin a new session.
258
+ * @returns A promise that resolves when the connection is established and the session begins.
259
+ */
244
260
  connect() {
245
261
  return new Promise((resolve) => {
246
262
  if (this.socket) {
@@ -319,9 +335,17 @@ class RealtimeTranscriber {
319
335
  };
320
336
  });
321
337
  }
338
+ /**
339
+ * Send audio data to the server.
340
+ * @param audio - The audio data to send to the server.
341
+ */
322
342
  sendAudio(audio) {
323
343
  this.send(audio);
324
344
  }
345
+ /**
346
+ * Create a writable stream that can be used to send audio data to the server.
347
+ * @returns A writable stream that can be used to send audio data to the server.
348
+ */
325
349
  stream() {
326
350
  return new WritableStream({
327
351
  write: (chunk) => {
@@ -349,6 +373,11 @@ class RealtimeTranscriber {
349
373
  }
350
374
  this.socket.send(data);
351
375
  }
376
+ /**
377
+ * Close the connection to the server.
378
+ * @param waitForSessionTermination - If true, the method will wait for the session to be terminated before closing the connection.
379
+ * While waiting for the session to be terminated, you will receive the final transcript and session information.
380
+ */
352
381
  async close(waitForSessionTermination = true) {
353
382
  if (this.socket) {
354
383
  if (this.socket.readyState === this.socket.OPEN) {
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.5.0" },
20
+ sdk: { name: "JavaScript", version: "4.6.0" },
21
21
  };
22
22
  if (typeof process !== "undefined") {
23
23
  if (process.versions.node && defaultUserAgentString.indexOf("Node") === -1) {
@@ -193,7 +193,14 @@ class RealtimeError extends Error {
193
193
  const defaultRealtimeUrl = "wss://api.assemblyai.com/v2/realtime/ws";
194
194
  const forceEndOfUtteranceMessage = `{"force_end_utterance":true}`;
195
195
  const terminateSessionMessage = `{"terminate_session":true}`;
196
+ /**
197
+ * RealtimeTranscriber connects to the Streaming Speech-to-Text API and lets you transcribe audio in real-time.
198
+ */
196
199
  class RealtimeTranscriber {
200
+ /**
201
+ * Create a new RealtimeTranscriber.
202
+ * @param params - Parameters to configure the RealtimeTranscriber
203
+ */
197
204
  constructor(params) {
198
205
  this.listeners = {};
199
206
  this.realtimeUrl = params.realtimeUrl ?? defaultRealtimeUrl;
@@ -233,10 +240,19 @@ class RealtimeTranscriber {
233
240
  url.search = searchParams.toString();
234
241
  return url;
235
242
  }
243
+ /**
244
+ * Add a listener for an event.
245
+ * @param event - The event to listen for.
246
+ * @param listener - The function to call when the event is emitted.
247
+ */
236
248
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
237
249
  on(event, listener) {
238
250
  this.listeners[event] = listener;
239
251
  }
252
+ /**
253
+ * Connect to the server and begin a new session.
254
+ * @returns A promise that resolves when the connection is established and the session begins.
255
+ */
240
256
  connect() {
241
257
  return new Promise((resolve) => {
242
258
  if (this.socket) {
@@ -315,9 +331,17 @@ class RealtimeTranscriber {
315
331
  };
316
332
  });
317
333
  }
334
+ /**
335
+ * Send audio data to the server.
336
+ * @param audio - The audio data to send to the server.
337
+ */
318
338
  sendAudio(audio) {
319
339
  this.send(audio);
320
340
  }
341
+ /**
342
+ * Create a writable stream that can be used to send audio data to the server.
343
+ * @returns A writable stream that can be used to send audio data to the server.
344
+ */
321
345
  stream() {
322
346
  return new WritableStream({
323
347
  write: (chunk) => {
@@ -345,6 +369,11 @@ class RealtimeTranscriber {
345
369
  }
346
370
  this.socket.send(data);
347
371
  }
372
+ /**
373
+ * Close the connection to the server.
374
+ * @param waitForSessionTermination - If true, the method will wait for the session to be terminated before closing the connection.
375
+ * While waiting for the session to be terminated, you will receive the final transcript and session information.
376
+ */
348
377
  async close(waitForSessionTermination = true) {
349
378
  if (this.socket) {
350
379
  if (this.socket.readyState === this.socket.OPEN) {
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.5.0" },
20
+ sdk: { name: "JavaScript", version: "4.6.0" },
21
21
  };
22
22
  if (typeof process !== "undefined") {
23
23
  if (process.versions.node && defaultUserAgentString.indexOf("Node") === -1) {
@@ -193,7 +193,14 @@ class RealtimeError extends Error {
193
193
  const defaultRealtimeUrl = "wss://api.assemblyai.com/v2/realtime/ws";
194
194
  const forceEndOfUtteranceMessage = `{"force_end_utterance":true}`;
195
195
  const terminateSessionMessage = `{"terminate_session":true}`;
196
+ /**
197
+ * RealtimeTranscriber connects to the Streaming Speech-to-Text API and lets you transcribe audio in real-time.
198
+ */
196
199
  class RealtimeTranscriber {
200
+ /**
201
+ * Create a new RealtimeTranscriber.
202
+ * @param params - Parameters to configure the RealtimeTranscriber
203
+ */
197
204
  constructor(params) {
198
205
  this.listeners = {};
199
206
  this.realtimeUrl = params.realtimeUrl ?? defaultRealtimeUrl;
@@ -233,10 +240,19 @@ class RealtimeTranscriber {
233
240
  url.search = searchParams.toString();
234
241
  return url;
235
242
  }
243
+ /**
244
+ * Add a listener for an event.
245
+ * @param event - The event to listen for.
246
+ * @param listener - The function to call when the event is emitted.
247
+ */
236
248
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
237
249
  on(event, listener) {
238
250
  this.listeners[event] = listener;
239
251
  }
252
+ /**
253
+ * Connect to the server and begin a new session.
254
+ * @returns A promise that resolves when the connection is established and the session begins.
255
+ */
240
256
  connect() {
241
257
  return new Promise((resolve) => {
242
258
  if (this.socket) {
@@ -315,9 +331,17 @@ class RealtimeTranscriber {
315
331
  };
316
332
  });
317
333
  }
334
+ /**
335
+ * Send audio data to the server.
336
+ * @param audio - The audio data to send to the server.
337
+ */
318
338
  sendAudio(audio) {
319
339
  this.send(audio);
320
340
  }
341
+ /**
342
+ * Create a writable stream that can be used to send audio data to the server.
343
+ * @returns A writable stream that can be used to send audio data to the server.
344
+ */
321
345
  stream() {
322
346
  return new WritableStream({
323
347
  write: (chunk) => {
@@ -345,6 +369,11 @@ class RealtimeTranscriber {
345
369
  }
346
370
  this.socket.send(data);
347
371
  }
372
+ /**
373
+ * Close the connection to the server.
374
+ * @param waitForSessionTermination - If true, the method will wait for the session to be terminated before closing the connection.
375
+ * While waiting for the session to be terminated, you will receive the final transcript and session information.
376
+ */
348
377
  async close(waitForSessionTermination = true) {
349
378
  if (this.socket) {
350
379
  if (this.socket.readyState === this.socket.OPEN) {
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.5.0" },
66
+ sdk: { name: "JavaScript", version: "4.6.0" },
67
67
  };
68
68
  if (typeof process !== "undefined") {
69
69
  if (process.versions.node && defaultUserAgentString.indexOf("Node") === -1) {
@@ -243,7 +243,14 @@ class RealtimeError extends Error {
243
243
  const defaultRealtimeUrl = "wss://api.assemblyai.com/v2/realtime/ws";
244
244
  const forceEndOfUtteranceMessage = `{"force_end_utterance":true}`;
245
245
  const terminateSessionMessage = `{"terminate_session":true}`;
246
+ /**
247
+ * RealtimeTranscriber connects to the Streaming Speech-to-Text API and lets you transcribe audio in real-time.
248
+ */
246
249
  class RealtimeTranscriber {
250
+ /**
251
+ * Create a new RealtimeTranscriber.
252
+ * @param params - Parameters to configure the RealtimeTranscriber
253
+ */
247
254
  constructor(params) {
248
255
  var _a, _b;
249
256
  this.listeners = {};
@@ -284,10 +291,19 @@ class RealtimeTranscriber {
284
291
  url.search = searchParams.toString();
285
292
  return url;
286
293
  }
294
+ /**
295
+ * Add a listener for an event.
296
+ * @param event - The event to listen for.
297
+ * @param listener - The function to call when the event is emitted.
298
+ */
287
299
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
288
300
  on(event, listener) {
289
301
  this.listeners[event] = listener;
290
302
  }
303
+ /**
304
+ * Connect to the server and begin a new session.
305
+ * @returns A promise that resolves when the connection is established and the session begins.
306
+ */
291
307
  connect() {
292
308
  return new Promise((resolve) => {
293
309
  if (this.socket) {
@@ -369,9 +385,17 @@ class RealtimeTranscriber {
369
385
  };
370
386
  });
371
387
  }
388
+ /**
389
+ * Send audio data to the server.
390
+ * @param audio - The audio data to send to the server.
391
+ */
372
392
  sendAudio(audio) {
373
393
  this.send(audio);
374
394
  }
395
+ /**
396
+ * Create a writable stream that can be used to send audio data to the server.
397
+ * @returns A writable stream that can be used to send audio data to the server.
398
+ */
375
399
  stream() {
376
400
  return new WritableStream({
377
401
  write: (chunk) => {
@@ -399,6 +423,11 @@ class RealtimeTranscriber {
399
423
  }
400
424
  this.socket.send(data);
401
425
  }
426
+ /**
427
+ * Close the connection to the server.
428
+ * @param waitForSessionTermination - If true, the method will wait for the session to be terminated before closing the connection.
429
+ * While waiting for the session to be terminated, you will receive the final transcript and session information.
430
+ */
402
431
  close() {
403
432
  return __awaiter(this, arguments, void 0, function* (waitForSessionTermination = true) {
404
433
  var _a;
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.5.0" },
64
+ sdk: { name: "JavaScript", version: "4.6.0" },
65
65
  };
66
66
  if (typeof process !== "undefined") {
67
67
  if (process.versions.node && defaultUserAgentString.indexOf("Node") === -1) {
@@ -241,7 +241,14 @@ class RealtimeError extends Error {
241
241
  const defaultRealtimeUrl = "wss://api.assemblyai.com/v2/realtime/ws";
242
242
  const forceEndOfUtteranceMessage = `{"force_end_utterance":true}`;
243
243
  const terminateSessionMessage = `{"terminate_session":true}`;
244
+ /**
245
+ * RealtimeTranscriber connects to the Streaming Speech-to-Text API and lets you transcribe audio in real-time.
246
+ */
244
247
  class RealtimeTranscriber {
248
+ /**
249
+ * Create a new RealtimeTranscriber.
250
+ * @param params - Parameters to configure the RealtimeTranscriber
251
+ */
245
252
  constructor(params) {
246
253
  var _a, _b;
247
254
  this.listeners = {};
@@ -282,10 +289,19 @@ class RealtimeTranscriber {
282
289
  url.search = searchParams.toString();
283
290
  return url;
284
291
  }
292
+ /**
293
+ * Add a listener for an event.
294
+ * @param event - The event to listen for.
295
+ * @param listener - The function to call when the event is emitted.
296
+ */
285
297
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
286
298
  on(event, listener) {
287
299
  this.listeners[event] = listener;
288
300
  }
301
+ /**
302
+ * Connect to the server and begin a new session.
303
+ * @returns A promise that resolves when the connection is established and the session begins.
304
+ */
289
305
  connect() {
290
306
  return new Promise((resolve) => {
291
307
  if (this.socket) {
@@ -367,9 +383,17 @@ class RealtimeTranscriber {
367
383
  };
368
384
  });
369
385
  }
386
+ /**
387
+ * Send audio data to the server.
388
+ * @param audio - The audio data to send to the server.
389
+ */
370
390
  sendAudio(audio) {
371
391
  this.send(audio);
372
392
  }
393
+ /**
394
+ * Create a writable stream that can be used to send audio data to the server.
395
+ * @returns A writable stream that can be used to send audio data to the server.
396
+ */
373
397
  stream() {
374
398
  return new WritableStream({
375
399
  write: (chunk) => {
@@ -397,6 +421,11 @@ class RealtimeTranscriber {
397
421
  }
398
422
  this.socket.send(data);
399
423
  }
424
+ /**
425
+ * Close the connection to the server.
426
+ * @param waitForSessionTermination - If true, the method will wait for the session to be terminated before closing the connection.
427
+ * While waiting for the session to be terminated, you will receive the final transcript and session information.
428
+ */
400
429
  close() {
401
430
  return __awaiter(this, arguments, void 0, function* (waitForSessionTermination = true) {
402
431
  var _a;
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.5.0" },
25
+ sdk: { name: "JavaScript", version: "4.6.0" },
26
26
  };
27
27
  if (typeof process !== "undefined") {
28
28
  if (process.versions.node && defaultUserAgentString.indexOf("Node") === -1) {
@@ -192,7 +192,14 @@ class RealtimeError extends Error {
192
192
  const defaultRealtimeUrl = "wss://api.assemblyai.com/v2/realtime/ws";
193
193
  const forceEndOfUtteranceMessage = `{"force_end_utterance":true}`;
194
194
  const terminateSessionMessage = `{"terminate_session":true}`;
195
+ /**
196
+ * RealtimeTranscriber connects to the Streaming Speech-to-Text API and lets you transcribe audio in real-time.
197
+ */
195
198
  class RealtimeTranscriber {
199
+ /**
200
+ * Create a new RealtimeTranscriber.
201
+ * @param params - Parameters to configure the RealtimeTranscriber
202
+ */
196
203
  constructor(params) {
197
204
  this.listeners = {};
198
205
  this.realtimeUrl = params.realtimeUrl ?? defaultRealtimeUrl;
@@ -232,10 +239,19 @@ class RealtimeTranscriber {
232
239
  url.search = searchParams.toString();
233
240
  return url;
234
241
  }
242
+ /**
243
+ * Add a listener for an event.
244
+ * @param event - The event to listen for.
245
+ * @param listener - The function to call when the event is emitted.
246
+ */
235
247
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
236
248
  on(event, listener) {
237
249
  this.listeners[event] = listener;
238
250
  }
251
+ /**
252
+ * Connect to the server and begin a new session.
253
+ * @returns A promise that resolves when the connection is established and the session begins.
254
+ */
239
255
  connect() {
240
256
  return new Promise((resolve) => {
241
257
  if (this.socket) {
@@ -314,9 +330,17 @@ class RealtimeTranscriber {
314
330
  };
315
331
  });
316
332
  }
333
+ /**
334
+ * Send audio data to the server.
335
+ * @param audio - The audio data to send to the server.
336
+ */
317
337
  sendAudio(audio) {
318
338
  this.send(audio);
319
339
  }
340
+ /**
341
+ * Create a writable stream that can be used to send audio data to the server.
342
+ * @returns A writable stream that can be used to send audio data to the server.
343
+ */
320
344
  stream() {
321
345
  return new web.WritableStream({
322
346
  write: (chunk) => {
@@ -344,6 +368,11 @@ class RealtimeTranscriber {
344
368
  }
345
369
  this.socket.send(data);
346
370
  }
371
+ /**
372
+ * Close the connection to the server.
373
+ * @param waitForSessionTermination - If true, the method will wait for the session to be terminated before closing the connection.
374
+ * While waiting for the session to be terminated, you will receive the final transcript and session information.
375
+ */
347
376
  async close(waitForSessionTermination = true) {
348
377
  if (this.socket) {
349
378
  if (this.socket.readyState === this.socket.OPEN) {