assemblyai 4.13.1 → 4.13.3

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/README.md CHANGED
@@ -13,7 +13,7 @@
13
13
  # AssemblyAI JavaScript SDK
14
14
 
15
15
  The AssemblyAI JavaScript SDK provides an easy-to-use interface for interacting with the AssemblyAI API,
16
- which supports async and real-time transcription, as well as the latest LeMUR models.
16
+ which supports async and streaming transcription, as well as the latest LeMUR models.
17
17
  It is written primarily for Node.js in TypeScript with all types exported, but also [compatible with other runtimes](./docs/compat.md).
18
18
 
19
19
  ## Documentation
@@ -73,11 +73,11 @@ You can use automatic CDNs like [UNPKG](https://unpkg.com/) to load the library
73
73
  ```
74
74
 
75
75
  The script creates a global `assemblyai` variable containing all the services.
76
- Here's how you create a `RealtimeTranscriber` object.
76
+ Here's how you create a `StreamingTranscriber` object.
77
77
 
78
78
  ```js
79
- const { RealtimeTranscriber } = assemblyai;
80
- const transcriber = new RealtimeTranscriber({
79
+ const { StreamingTranscriber } = assemblyai;
80
+ const transcriber = new StreamingTranscriber({
81
81
  token: "[GENERATE TEMPORARY AUTH TOKEN IN YOUR API]",
82
82
  ...
83
83
  });
@@ -101,7 +101,7 @@ let transcript = await client.transcripts.transcribe({
101
101
  });
102
102
  ```
103
103
 
104
- > **Note**
104
+ > [!NOTE]
105
105
  > You can also pass a local file path, a stream, or a buffer as the `audio` property.
106
106
 
107
107
  `transcribe` queues a transcription job and polls it until the `status` is `completed` or `error`.
@@ -242,20 +242,18 @@ const res = await client.transcripts.delete(transcript.id);
242
242
 
243
243
  ### Transcribe in real-time
244
244
 
245
- Create the real-time transcriber.
245
+ Create the streaming transcriber.
246
246
 
247
247
  ```typescript
248
- const rt = client.realtime.transcriber();
248
+ const rt = client.streaming.transcriber();
249
249
  ```
250
250
 
251
251
  You can also pass in the following options.
252
252
 
253
253
  ```typescript
254
- const rt = client.realtime.transcriber({
255
- realtimeUrl: 'wss://localhost/override',
254
+ const rt = client.streaming.transcriber({
256
255
  apiKey: process.env.ASSEMBLYAI_API_KEY // The API key passed to `AssemblyAI` will be used by default,
257
256
  sampleRate: 16_000,
258
- wordBoost: ['foo', 'bar']
259
257
  });
260
258
  ```
261
259
 
@@ -265,17 +263,19 @@ const rt = client.realtime.transcriber({
265
263
  > _Server code_:
266
264
  >
267
265
  > ```typescript
268
- > const token = await client.realtime.createTemporaryToken({ expires_in = 60 });
266
+ > const token = await client.streaming.createTemporaryToken({
267
+ > expires_in_seconds = 60,
268
+ > });
269
269
  > // TODO: return token to client
270
270
  > ```
271
271
  >
272
272
  > _Client code_:
273
273
  >
274
274
  > ```typescript
275
- > import { RealtimeTranscriber } from "assemblyai"; // or "assemblyai/streaming"
275
+ > import { StreamingTranscriber } from "assemblyai";
276
276
  > // TODO: implement getToken to retrieve token from server
277
277
  > const token = await getToken();
278
- > const rt = new RealtimeTranscriber({
278
+ > const rt = new StreamingTranscriber({
279
279
  > token,
280
280
  > });
281
281
  > ```
@@ -284,11 +284,9 @@ You can configure the following events.
284
284
 
285
285
  <!-- prettier-ignore -->
286
286
  ```typescript
287
- rt.on("open", ({ sessionId, expiresAt }) => console.log('Session ID:', sessionId, 'Expires at:', expiresAt));
287
+ rt.on("open", ({ id, expires_at }) => console.log('Session ID:', id, 'Expires at:', expires_at));
288
288
  rt.on("close", (code: number, reason: string) => console.log('Closed', code, reason));
289
- rt.on("transcript", (transcript: TranscriptMessage) => console.log('Transcript:', transcript));
290
- rt.on("transcript.partial", (transcript: PartialTranscriptMessage) => console.log('Partial transcript:', transcript));
291
- rt.on("transcript.final", (transcript: FinalTranscriptMessage) => console.log('Final transcript:', transcript));
289
+ rt.on("turn", ({ transcript }) => console.log('Transcript:', transcript));
292
290
  rt.on("error", (error: Error) => console.error('Error', error));
293
291
  ```
294
292
 
@@ -307,7 +305,7 @@ getAudio((chunk) => {
307
305
  });
308
306
  ```
309
307
 
310
- Or send audio data via a stream by piping to the real-time stream.
308
+ Or send audio data via a stream:
311
309
 
312
310
  ```typescript
313
311
  audioStream.pipeTo(rt.stream());
@@ -65,7 +65,7 @@
65
65
  defaultUserAgentString += navigator.userAgent;
66
66
  }
67
67
  const defaultUserAgent = {
68
- sdk: { name: "JavaScript", version: "4.13.1" },
68
+ sdk: { name: "JavaScript", version: "4.13.3" },
69
69
  };
70
70
  if (typeof process !== "undefined") {
71
71
  if (process.versions.node && defaultUserAgentString.indexOf("Node") === -1) {
@@ -893,6 +893,9 @@ Learn more at https://github.com/AssemblyAI/assemblyai-node-sdk/blob/main/docs/c
893
893
  throw new Error("Invalid protocol, must be wss");
894
894
  }
895
895
  const searchParams = new URLSearchParams();
896
+ if (this.token) {
897
+ searchParams.set("token", this.token);
898
+ }
896
899
  searchParams.set("sample_rate", this.params.sampleRate.toString());
897
900
  if (this.params.endOfTurnConfidenceThreshold) {
898
901
  searchParams.set("end_of_turn_confidence_threshold", this.params.endOfTurnConfidenceThreshold.toString());
@@ -919,9 +922,18 @@ Learn more at https://github.com/AssemblyAI/assemblyai-node-sdk/blob/main/docs/c
919
922
  throw new Error("Already connected");
920
923
  }
921
924
  const url = this.connectionUrl();
922
- this.socket = factory(url.toString(), {
923
- headers: { Authorization: this.token || this.apiKey },
924
- });
925
+ if (this.token) {
926
+ this.socket = factory(url.toString());
927
+ }
928
+ else {
929
+ {
930
+ console.warn(`API key authentication is not supported for the StreamingTranscriber in browser environment. Use temporary token authentication instead.
931
+ Learn more at https://github.com/AssemblyAI/assemblyai-node-sdk/blob/main/docs/compat.md#browser-compatibility.`);
932
+ }
933
+ this.socket = factory(url.toString(), {
934
+ headers: { Authorization: this.apiKey },
935
+ });
936
+ }
925
937
  this.socket.binaryType = "arraybuffer";
926
938
  this.socket.onopen = () => { };
927
939
  this.socket.onclose = ({ code, reason }) => {
@@ -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.13.1"}};"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){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,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 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===(r=(n=this.listeners).open)||void 0===r||r.call(n,t);break}case"PartialTranscript":b.created=new Date(b.created),null===(a=(o=this.listeners).transcript)||void 0===a||a.call(o,b),null===(l=(c=this.listeners)["transcript.partial"])||void 0===l||l.call(c,b);break;case"FinalTranscript":b.created=new Date(b.created),null===(h=(d=this.listeners).transcript)||void 0===h||h.call(d,b),null===(m=(u=this.listeners)["transcript.final"])||void 0===m||m.call(u,b);break;case"SessionInformation":null===(v=(f=this.listeners).session_information)||void 0===v||v.call(f,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(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 b 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 w(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 g 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=w(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=w(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 s.set("sample_rate",this.params.sampleRate.toString()),this.params.endOfTurnConfidenceThreshold&&s.set("end_of_turn_confidence_threshold",this.params.endOfTurnConfidenceThreshold.toString()),this.params.minEndOfTurnSilenceWhenConfident&&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()),this.params.formatTurns&&s.set("format_turns",this.params.formatTurns.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.socket=h(t.toString(),{headers:{Authorization:this.token||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)}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 g(e,this.files),this.lemur=new o(e),this.realtime=new b(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 b{},e.RealtimeTranscriber=y,e.RealtimeTranscriberFactory=b,e.StreamingTranscriber=T,e.TranscriptService=g}));
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.13.3"}};"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){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,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 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===(r=(n=this.listeners).open)||void 0===r||r.call(n,t);break}case"PartialTranscript":b.created=new Date(b.created),null===(a=(o=this.listeners).transcript)||void 0===a||a.call(o,b),null===(l=(c=this.listeners)["transcript.partial"])||void 0===l||l.call(c,b);break;case"FinalTranscript":b.created=new Date(b.created),null===(h=(d=this.listeners).transcript)||void 0===h||h.call(d,b),null===(m=(u=this.listeners)["transcript.final"])||void 0===m||m.call(u,b);break;case"SessionInformation":null===(v=(f=this.listeners).session_information)||void 0===v||v.call(f,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(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 b 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 w(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 g 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=w(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=w(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 k 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 S='{"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.minEndOfTurnSilenceWhenConfident&&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()),this.params.formatTurns&&s.set("format_turns",this.params.formatTurns.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)}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(S),yield e}else this.socket.send(S);(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 k(e),this.transcripts=new g(e,this.files),this.lemur=new o(e),this.realtime=new b(e),this.streaming=new O(Object.assign(Object.assign({},e),{baseUrl:e.streamingBaseUrl||"https://streaming.assemblyai.com"}))}},e.FileService=k,e.LemurService=o,e.RealtimeService=class extends y{},e.RealtimeServiceFactory=class extends b{},e.RealtimeTranscriber=y,e.RealtimeTranscriberFactory=b,e.StreamingTranscriber=T,e.TranscriptService=g}));
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.13.1" },
18
+ sdk: { name: "JavaScript", version: "4.13.3" },
19
19
  };
20
20
  if (typeof process !== "undefined") {
21
21
  if (process.versions.node && defaultUserAgentString.indexOf("Node") === -1) {
@@ -808,6 +808,9 @@ class StreamingTranscriber {
808
808
  throw new Error("Invalid protocol, must be wss");
809
809
  }
810
810
  const searchParams = new URLSearchParams();
811
+ if (this.token) {
812
+ searchParams.set("token", this.token);
813
+ }
811
814
  searchParams.set("sample_rate", this.params.sampleRate.toString());
812
815
  if (this.params.endOfTurnConfidenceThreshold) {
813
816
  searchParams.set("end_of_turn_confidence_threshold", this.params.endOfTurnConfidenceThreshold.toString());
@@ -834,9 +837,18 @@ class StreamingTranscriber {
834
837
  throw new Error("Already connected");
835
838
  }
836
839
  const url = this.connectionUrl();
837
- this.socket = factory(url.toString(), {
838
- headers: { Authorization: this.token || this.apiKey },
839
- });
840
+ if (this.token) {
841
+ this.socket = factory(url.toString());
842
+ }
843
+ else {
844
+ {
845
+ console.warn(`API key authentication is not supported for the StreamingTranscriber in browser environment. Use temporary token authentication instead.
846
+ Learn more at https://github.com/AssemblyAI/assemblyai-node-sdk/blob/main/docs/compat.md#browser-compatibility.`);
847
+ }
848
+ this.socket = factory(url.toString(), {
849
+ headers: { Authorization: this.apiKey },
850
+ });
851
+ }
840
852
  this.socket.binaryType = "arraybuffer";
841
853
  this.socket.onopen = () => { };
842
854
  this.socket.onclose = ({ code, reason }) => {
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.13.1" },
20
+ sdk: { name: "JavaScript", version: "4.13.3" },
21
21
  };
22
22
  if (typeof process !== "undefined") {
23
23
  if (process.versions.node && defaultUserAgentString.indexOf("Node") === -1) {
@@ -789,6 +789,9 @@ class StreamingTranscriber {
789
789
  throw new Error("Invalid protocol, must be wss");
790
790
  }
791
791
  const searchParams = new URLSearchParams();
792
+ if (this.token) {
793
+ searchParams.set("token", this.token);
794
+ }
792
795
  searchParams.set("sample_rate", this.params.sampleRate.toString());
793
796
  if (this.params.endOfTurnConfidenceThreshold) {
794
797
  searchParams.set("end_of_turn_confidence_threshold", this.params.endOfTurnConfidenceThreshold.toString());
@@ -815,9 +818,14 @@ class StreamingTranscriber {
815
818
  throw new Error("Already connected");
816
819
  }
817
820
  const url = this.connectionUrl();
818
- this.socket = factory(url.toString(), {
819
- headers: { Authorization: this.token || this.apiKey },
820
- });
821
+ if (this.token) {
822
+ this.socket = factory(url.toString());
823
+ }
824
+ else {
825
+ this.socket = factory(url.toString(), {
826
+ headers: { Authorization: this.apiKey },
827
+ });
828
+ }
821
829
  this.socket.binaryType = "arraybuffer";
822
830
  this.socket.onopen = () => { };
823
831
  this.socket.onclose = ({ code, reason }) => {
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.13.1" },
20
+ sdk: { name: "JavaScript", version: "4.13.3" },
21
21
  };
22
22
  if (typeof process !== "undefined") {
23
23
  if (process.versions.node && defaultUserAgentString.indexOf("Node") === -1) {
@@ -789,6 +789,9 @@ class StreamingTranscriber {
789
789
  throw new Error("Invalid protocol, must be wss");
790
790
  }
791
791
  const searchParams = new URLSearchParams();
792
+ if (this.token) {
793
+ searchParams.set("token", this.token);
794
+ }
792
795
  searchParams.set("sample_rate", this.params.sampleRate.toString());
793
796
  if (this.params.endOfTurnConfidenceThreshold) {
794
797
  searchParams.set("end_of_turn_confidence_threshold", this.params.endOfTurnConfidenceThreshold.toString());
@@ -815,9 +818,14 @@ class StreamingTranscriber {
815
818
  throw new Error("Already connected");
816
819
  }
817
820
  const url = this.connectionUrl();
818
- this.socket = factory(url.toString(), {
819
- headers: { Authorization: this.token || this.apiKey },
820
- });
821
+ if (this.token) {
822
+ this.socket = factory(url.toString());
823
+ }
824
+ else {
825
+ this.socket = factory(url.toString(), {
826
+ headers: { Authorization: this.apiKey },
827
+ });
828
+ }
821
829
  this.socket.binaryType = "arraybuffer";
822
830
  this.socket.onopen = () => { };
823
831
  this.socket.onclose = ({ code, reason }) => {
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.13.1" },
66
+ sdk: { name: "JavaScript", version: "4.13.3" },
67
67
  };
68
68
  if (typeof process !== "undefined") {
69
69
  if (process.versions.node && defaultUserAgentString.indexOf("Node") === -1) {
@@ -880,6 +880,9 @@ class StreamingTranscriber {
880
880
  throw new Error("Invalid protocol, must be wss");
881
881
  }
882
882
  const searchParams = new URLSearchParams();
883
+ if (this.token) {
884
+ searchParams.set("token", this.token);
885
+ }
883
886
  searchParams.set("sample_rate", this.params.sampleRate.toString());
884
887
  if (this.params.endOfTurnConfidenceThreshold) {
885
888
  searchParams.set("end_of_turn_confidence_threshold", this.params.endOfTurnConfidenceThreshold.toString());
@@ -906,9 +909,14 @@ class StreamingTranscriber {
906
909
  throw new Error("Already connected");
907
910
  }
908
911
  const url = this.connectionUrl();
909
- this.socket = factory(url.toString(), {
910
- headers: { Authorization: this.token || this.apiKey },
911
- });
912
+ if (this.token) {
913
+ this.socket = factory(url.toString());
914
+ }
915
+ else {
916
+ this.socket = factory(url.toString(), {
917
+ headers: { Authorization: this.apiKey },
918
+ });
919
+ }
912
920
  this.socket.binaryType = "arraybuffer";
913
921
  this.socket.onopen = () => { };
914
922
  this.socket.onclose = ({ code, reason }) => {
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.13.1" },
64
+ sdk: { name: "JavaScript", version: "4.13.3" },
65
65
  };
66
66
  if (typeof process !== "undefined") {
67
67
  if (process.versions.node && defaultUserAgentString.indexOf("Node") === -1) {
@@ -878,6 +878,9 @@ class StreamingTranscriber {
878
878
  throw new Error("Invalid protocol, must be wss");
879
879
  }
880
880
  const searchParams = new URLSearchParams();
881
+ if (this.token) {
882
+ searchParams.set("token", this.token);
883
+ }
881
884
  searchParams.set("sample_rate", this.params.sampleRate.toString());
882
885
  if (this.params.endOfTurnConfidenceThreshold) {
883
886
  searchParams.set("end_of_turn_confidence_threshold", this.params.endOfTurnConfidenceThreshold.toString());
@@ -904,9 +907,14 @@ class StreamingTranscriber {
904
907
  throw new Error("Already connected");
905
908
  }
906
909
  const url = this.connectionUrl();
907
- this.socket = factory(url.toString(), {
908
- headers: { Authorization: this.token || this.apiKey },
909
- });
910
+ if (this.token) {
911
+ this.socket = factory(url.toString());
912
+ }
913
+ else {
914
+ this.socket = factory(url.toString(), {
915
+ headers: { Authorization: this.apiKey },
916
+ });
917
+ }
910
918
  this.socket.binaryType = "arraybuffer";
911
919
  this.socket.onopen = () => { };
912
920
  this.socket.onclose = ({ code, reason }) => {
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.13.1" },
25
+ sdk: { name: "JavaScript", version: "4.13.3" },
26
26
  };
27
27
  if (typeof process !== "undefined") {
28
28
  if (process.versions.node && defaultUserAgentString.indexOf("Node") === -1) {
@@ -788,6 +788,9 @@ class StreamingTranscriber {
788
788
  throw new Error("Invalid protocol, must be wss");
789
789
  }
790
790
  const searchParams = new URLSearchParams();
791
+ if (this.token) {
792
+ searchParams.set("token", this.token);
793
+ }
791
794
  searchParams.set("sample_rate", this.params.sampleRate.toString());
792
795
  if (this.params.endOfTurnConfidenceThreshold) {
793
796
  searchParams.set("end_of_turn_confidence_threshold", this.params.endOfTurnConfidenceThreshold.toString());
@@ -814,9 +817,14 @@ class StreamingTranscriber {
814
817
  throw new Error("Already connected");
815
818
  }
816
819
  const url = this.connectionUrl();
817
- this.socket = factory(url.toString(), {
818
- headers: { Authorization: this.token || this.apiKey },
819
- });
820
+ if (this.token) {
821
+ this.socket = factory(url.toString());
822
+ }
823
+ else {
824
+ this.socket = factory(url.toString(), {
825
+ headers: { Authorization: this.apiKey },
826
+ });
827
+ }
820
828
  this.socket.binaryType = "arraybuffer";
821
829
  this.socket.onopen = () => { };
822
830
  this.socket.onclose = ({ code, reason }) => {
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.13.1" },
23
+ sdk: { name: "JavaScript", version: "4.13.3" },
24
24
  };
25
25
  if (typeof process !== "undefined") {
26
26
  if (process.versions.node && defaultUserAgentString.indexOf("Node") === -1) {
@@ -786,6 +786,9 @@ class StreamingTranscriber {
786
786
  throw new Error("Invalid protocol, must be wss");
787
787
  }
788
788
  const searchParams = new URLSearchParams();
789
+ if (this.token) {
790
+ searchParams.set("token", this.token);
791
+ }
789
792
  searchParams.set("sample_rate", this.params.sampleRate.toString());
790
793
  if (this.params.endOfTurnConfidenceThreshold) {
791
794
  searchParams.set("end_of_turn_confidence_threshold", this.params.endOfTurnConfidenceThreshold.toString());
@@ -812,9 +815,14 @@ class StreamingTranscriber {
812
815
  throw new Error("Already connected");
813
816
  }
814
817
  const url = this.connectionUrl();
815
- this.socket = factory(url.toString(), {
816
- headers: { Authorization: this.token || this.apiKey },
817
- });
818
+ if (this.token) {
819
+ this.socket = factory(url.toString());
820
+ }
821
+ else {
822
+ this.socket = factory(url.toString(), {
823
+ headers: { Authorization: this.apiKey },
824
+ });
825
+ }
818
826
  this.socket.binaryType = "arraybuffer";
819
827
  this.socket.onopen = () => { };
820
828
  this.socket.onclose = ({ code, reason }) => {
@@ -1259,6 +1259,19 @@ export type SeverityScoreSummary = {
1259
1259
  low: number;
1260
1260
  medium: number;
1261
1261
  };
1262
+ /**
1263
+ * Advanced options for controlling speaker diarization parameters
1264
+ */
1265
+ export type SpeakerOptions = {
1266
+ /**
1267
+ * Minimum number of speakers expected in the audio
1268
+ */
1269
+ min_speakers_expected?: number | null;
1270
+ /**
1271
+ * Maximum number of speakers expected in the audio
1272
+ */
1273
+ max_speakers_expected?: number | null;
1274
+ };
1262
1275
  /**
1263
1276
  * The speech model to use for the transcription.
1264
1277
  */
@@ -2350,6 +2363,10 @@ export type Transcript = {
2350
2363
  * Tell the speaker label model how many speakers it should attempt to identify, up to 10. See {@link https://www.assemblyai.com/docs/models/speaker-diarization | Speaker diarization } for more details.
2351
2364
  */
2352
2365
  speakers_expected?: number | null;
2366
+ /**
2367
+ * Advanced options for controlling speaker diarization parameters
2368
+ */
2369
+ speaker_options?: SpeakerOptions | null;
2353
2370
  /**
2354
2371
  * The speech model used for the transcription. When `null`, the default model is used.
2355
2372
  * @defaultValue "null
@@ -2764,6 +2781,10 @@ export type TranscriptOptionalParams = {
2764
2781
  * @defaultValue "null
2765
2782
  */
2766
2783
  speakers_expected?: number | null;
2784
+ /**
2785
+ * Advanced options for controlling speaker diarization parameters
2786
+ */
2787
+ speaker_options?: SpeakerOptions | null;
2767
2788
  /**
2768
2789
  * The speech model to use for the transcription. When `null`, the "best" model is used.
2769
2790
  * @defaultValue best
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.13.1" },
18
+ sdk: { name: "JavaScript", version: "4.13.3" },
19
19
  };
20
20
  if (typeof process !== "undefined") {
21
21
  if (process.versions.node && defaultUserAgentString.indexOf("Node") === -1) {
@@ -791,6 +791,9 @@ class StreamingTranscriber {
791
791
  throw new Error("Invalid protocol, must be wss");
792
792
  }
793
793
  const searchParams = new URLSearchParams();
794
+ if (this.token) {
795
+ searchParams.set("token", this.token);
796
+ }
794
797
  searchParams.set("sample_rate", this.params.sampleRate.toString());
795
798
  if (this.params.endOfTurnConfidenceThreshold) {
796
799
  searchParams.set("end_of_turn_confidence_threshold", this.params.endOfTurnConfidenceThreshold.toString());
@@ -817,9 +820,14 @@ class StreamingTranscriber {
817
820
  throw new Error("Already connected");
818
821
  }
819
822
  const url = this.connectionUrl();
820
- this.socket = factory(url.toString(), {
821
- headers: { Authorization: this.token || this.apiKey },
822
- });
823
+ if (this.token) {
824
+ this.socket = factory(url.toString());
825
+ }
826
+ else {
827
+ this.socket = factory(url.toString(), {
828
+ headers: { Authorization: this.apiKey },
829
+ });
830
+ }
823
831
  this.socket.binaryType = "arraybuffer";
824
832
  this.socket.onopen = () => { };
825
833
  this.socket.onclose = ({ code, reason }) => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "assemblyai",
3
- "version": "4.13.1",
3
+ "version": "4.13.3",
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"
@@ -4,6 +4,7 @@ import {
4
4
  factory as polyfillWebSocketFactory,
5
5
  } from "#websocket";
6
6
  import { ErrorEvent, MessageEvent, CloseEvent } from "ws";
7
+ import { conditions } from "#conditions";
7
8
  import {
8
9
  StreamingEvents,
9
10
  StreamingListeners,
@@ -69,6 +70,10 @@ export class StreamingTranscriber {
69
70
 
70
71
  const searchParams = new URLSearchParams();
71
72
 
73
+ if (this.token) {
74
+ searchParams.set("token", this.token);
75
+ }
76
+
72
77
  searchParams.set("sample_rate", this.params.sampleRate.toString());
73
78
 
74
79
  if (this.params.endOfTurnConfidenceThreshold) {
@@ -118,9 +123,20 @@ export class StreamingTranscriber {
118
123
 
119
124
  const url = this.connectionUrl();
120
125
 
121
- this.socket = polyfillWebSocketFactory(url.toString(), {
122
- headers: { Authorization: this.token || this.apiKey },
123
- });
126
+ if (this.token) {
127
+ this.socket = polyfillWebSocketFactory(url.toString());
128
+ } else {
129
+ if (conditions.browser) {
130
+ console.warn(
131
+ `API key authentication is not supported for the StreamingTranscriber in browser environment. Use temporary token authentication instead.
132
+ Learn more at https://github.com/AssemblyAI/assemblyai-node-sdk/blob/main/docs/compat.md#browser-compatibility.`,
133
+ );
134
+ }
135
+
136
+ this.socket = polyfillWebSocketFactory(url.toString(), {
137
+ headers: { Authorization: this.apiKey },
138
+ });
139
+ }
124
140
 
125
141
  this.socket.binaryType = "arraybuffer";
126
142
 
@@ -1413,6 +1413,20 @@ export type SeverityScoreSummary = {
1413
1413
  medium: number;
1414
1414
  };
1415
1415
 
1416
+ /**
1417
+ * Advanced options for controlling speaker diarization parameters
1418
+ */
1419
+ export type SpeakerOptions = {
1420
+ /**
1421
+ * Minimum number of speakers expected in the audio
1422
+ */
1423
+ min_speakers_expected?: number | null;
1424
+ /**
1425
+ * Maximum number of speakers expected in the audio
1426
+ */
1427
+ max_speakers_expected?: number | null;
1428
+ };
1429
+
1416
1430
  /**
1417
1431
  * The speech model to use for the transcription.
1418
1432
  */
@@ -2517,6 +2531,10 @@ export type Transcript = {
2517
2531
  * Tell the speaker label model how many speakers it should attempt to identify, up to 10. See {@link https://www.assemblyai.com/docs/models/speaker-diarization | Speaker diarization } for more details.
2518
2532
  */
2519
2533
  speakers_expected?: number | null;
2534
+ /**
2535
+ * Advanced options for controlling speaker diarization parameters
2536
+ */
2537
+ speaker_options?: SpeakerOptions | null;
2520
2538
  /**
2521
2539
  * The speech model used for the transcription. When `null`, the default model is used.
2522
2540
  * @defaultValue "null
@@ -3039,6 +3057,10 @@ export type TranscriptOptionalParams = {
3039
3057
  * @defaultValue "null
3040
3058
  */
3041
3059
  speakers_expected?: number | null;
3060
+ /**
3061
+ * Advanced options for controlling speaker diarization parameters
3062
+ */
3063
+ speaker_options?: SpeakerOptions | null;
3042
3064
  /**
3043
3065
  * The speech model to use for the transcription. When `null`, the "best" model is used.
3044
3066
  * @defaultValue best