assemblyai 4.4.2-beta.0 → 4.4.2-beta.2

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.
Files changed (2) hide show
  1. package/dist/browser.cjs +648 -0
  2. package/package.json +25 -4
@@ -0,0 +1,648 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Base class for services that communicate with the API.
5
+ */
6
+ class BaseService {
7
+ /**
8
+ * Create a new service.
9
+ * @param params - The parameters to use for the service.
10
+ */
11
+ constructor(params) {
12
+ this.params = params;
13
+ }
14
+ async fetch(input, init) {
15
+ init = init ?? {};
16
+ init.headers = init.headers ?? {};
17
+ init.headers = {
18
+ Authorization: this.params.apiKey,
19
+ "Content-Type": "application/json",
20
+ ...init.headers,
21
+ };
22
+ init.cache = "no-store";
23
+ if (!input.startsWith("http"))
24
+ input = this.params.baseUrl + input;
25
+ const response = await fetch(input, init);
26
+ if (response.status >= 400) {
27
+ let json;
28
+ const text = await response.text();
29
+ if (text) {
30
+ try {
31
+ json = JSON.parse(text);
32
+ }
33
+ catch {
34
+ /* empty */
35
+ }
36
+ if (json?.error)
37
+ throw new Error(json.error);
38
+ throw new Error(text);
39
+ }
40
+ throw new Error(`HTTP Error: ${response.status} ${response.statusText}`);
41
+ }
42
+ return response;
43
+ }
44
+ async fetchJson(input, init) {
45
+ const response = await this.fetch(input, init);
46
+ return response.json();
47
+ }
48
+ }
49
+
50
+ class LemurService extends BaseService {
51
+ summary(params) {
52
+ return this.fetchJson("/lemur/v3/generate/summary", {
53
+ method: "POST",
54
+ body: JSON.stringify(params),
55
+ });
56
+ }
57
+ questionAnswer(params) {
58
+ return this.fetchJson("/lemur/v3/generate/question-answer", {
59
+ method: "POST",
60
+ body: JSON.stringify(params),
61
+ });
62
+ }
63
+ actionItems(params) {
64
+ return this.fetchJson("/lemur/v3/generate/action-items", {
65
+ method: "POST",
66
+ body: JSON.stringify(params),
67
+ });
68
+ }
69
+ task(params) {
70
+ return this.fetchJson("/lemur/v3/generate/task", {
71
+ method: "POST",
72
+ body: JSON.stringify(params),
73
+ });
74
+ }
75
+ /**
76
+ * Delete the data for a previously submitted LeMUR request.
77
+ * @param id - ID of the LeMUR request
78
+ */
79
+ purgeRequestData(id) {
80
+ return this.fetchJson(`/lemur/v3/${id}`, {
81
+ method: "DELETE",
82
+ });
83
+ }
84
+ }
85
+
86
+ const { WritableStream } = typeof window !== "undefined"
87
+ ? window
88
+ : typeof global !== "undefined"
89
+ ? global
90
+ : globalThis;
91
+
92
+ const PolyfillWebSocket = WebSocket ?? global?.WebSocket ?? window?.WebSocket ?? self?.WebSocket;
93
+ const factory = (url, params) => {
94
+ if (params) {
95
+ return new PolyfillWebSocket(url, params);
96
+ }
97
+ return new PolyfillWebSocket(url);
98
+ };
99
+
100
+ var RealtimeErrorType;
101
+ (function (RealtimeErrorType) {
102
+ RealtimeErrorType[RealtimeErrorType["BadSampleRate"] = 4000] = "BadSampleRate";
103
+ RealtimeErrorType[RealtimeErrorType["AuthFailed"] = 4001] = "AuthFailed";
104
+ // Both InsufficientFunds and FreeAccount error use 4002
105
+ RealtimeErrorType[RealtimeErrorType["InsufficientFundsOrFreeAccount"] = 4002] = "InsufficientFundsOrFreeAccount";
106
+ RealtimeErrorType[RealtimeErrorType["NonexistentSessionId"] = 4004] = "NonexistentSessionId";
107
+ RealtimeErrorType[RealtimeErrorType["SessionExpired"] = 4008] = "SessionExpired";
108
+ RealtimeErrorType[RealtimeErrorType["ClosedSession"] = 4010] = "ClosedSession";
109
+ RealtimeErrorType[RealtimeErrorType["RateLimited"] = 4029] = "RateLimited";
110
+ RealtimeErrorType[RealtimeErrorType["UniqueSessionViolation"] = 4030] = "UniqueSessionViolation";
111
+ RealtimeErrorType[RealtimeErrorType["SessionTimeout"] = 4031] = "SessionTimeout";
112
+ RealtimeErrorType[RealtimeErrorType["AudioTooShort"] = 4032] = "AudioTooShort";
113
+ RealtimeErrorType[RealtimeErrorType["AudioTooLong"] = 4033] = "AudioTooLong";
114
+ RealtimeErrorType[RealtimeErrorType["BadJson"] = 4100] = "BadJson";
115
+ RealtimeErrorType[RealtimeErrorType["BadSchema"] = 4101] = "BadSchema";
116
+ RealtimeErrorType[RealtimeErrorType["TooManyStreams"] = 4102] = "TooManyStreams";
117
+ RealtimeErrorType[RealtimeErrorType["Reconnected"] = 4103] = "Reconnected";
118
+ RealtimeErrorType[RealtimeErrorType["ReconnectAttemptsExhausted"] = 1013] = "ReconnectAttemptsExhausted";
119
+ })(RealtimeErrorType || (RealtimeErrorType = {}));
120
+ const RealtimeErrorMessages = {
121
+ [RealtimeErrorType.BadSampleRate]: "Sample rate must be a positive integer",
122
+ [RealtimeErrorType.AuthFailed]: "Not Authorized",
123
+ [RealtimeErrorType.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.",
124
+ [RealtimeErrorType.NonexistentSessionId]: "Session ID does not exist",
125
+ [RealtimeErrorType.SessionExpired]: "Session has expired",
126
+ [RealtimeErrorType.ClosedSession]: "Session is closed",
127
+ [RealtimeErrorType.RateLimited]: "Rate limited",
128
+ [RealtimeErrorType.UniqueSessionViolation]: "Unique session violation",
129
+ [RealtimeErrorType.SessionTimeout]: "Session Timeout",
130
+ [RealtimeErrorType.AudioTooShort]: "Audio too short",
131
+ [RealtimeErrorType.AudioTooLong]: "Audio too long",
132
+ [RealtimeErrorType.BadJson]: "Bad JSON",
133
+ [RealtimeErrorType.BadSchema]: "Bad schema",
134
+ [RealtimeErrorType.TooManyStreams]: "Too many streams",
135
+ [RealtimeErrorType.Reconnected]: "Reconnected",
136
+ [RealtimeErrorType.ReconnectAttemptsExhausted]: "Reconnect attempts exhausted",
137
+ };
138
+ class RealtimeError extends Error {
139
+ }
140
+
141
+ const defaultRealtimeUrl = "wss://api.assemblyai.com/v2/realtime/ws";
142
+ const forceEndOfUtteranceMessage = `{"force_end_utterance":true}`;
143
+ const terminateSessionMessage = `{"terminate_session":true}`;
144
+ class RealtimeTranscriber {
145
+ constructor(params) {
146
+ this.listeners = {};
147
+ this.realtimeUrl = params.realtimeUrl ?? defaultRealtimeUrl;
148
+ this.sampleRate = params.sampleRate ?? 16_000;
149
+ this.wordBoost = params.wordBoost;
150
+ this.encoding = params.encoding;
151
+ this.endUtteranceSilenceThreshold = params.endUtteranceSilenceThreshold;
152
+ this.disablePartialTranscripts = params.disablePartialTranscripts;
153
+ if ("token" in params && params.token)
154
+ this.token = params.token;
155
+ if ("apiKey" in params && params.apiKey)
156
+ this.apiKey = params.apiKey;
157
+ if (!(this.token || this.apiKey)) {
158
+ throw new Error("API key or temporary token is required.");
159
+ }
160
+ }
161
+ connectionUrl() {
162
+ const url = new URL(this.realtimeUrl);
163
+ if (url.protocol !== "wss:") {
164
+ throw new Error("Invalid protocol, must be wss");
165
+ }
166
+ const searchParams = new URLSearchParams();
167
+ if (this.token) {
168
+ searchParams.set("token", this.token);
169
+ }
170
+ searchParams.set("sample_rate", this.sampleRate.toString());
171
+ if (this.wordBoost && this.wordBoost.length > 0) {
172
+ searchParams.set("word_boost", JSON.stringify(this.wordBoost));
173
+ }
174
+ if (this.encoding) {
175
+ searchParams.set("encoding", this.encoding);
176
+ }
177
+ searchParams.set("enable_extra_session_information", "true");
178
+ if (this.disablePartialTranscripts) {
179
+ searchParams.set("disable_partial_transcripts", this.disablePartialTranscripts.toString());
180
+ }
181
+ url.search = searchParams.toString();
182
+ return url;
183
+ }
184
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
185
+ on(event, listener) {
186
+ this.listeners[event] = listener;
187
+ }
188
+ connect() {
189
+ return new Promise((resolve) => {
190
+ if (this.socket) {
191
+ throw new Error("Already connected");
192
+ }
193
+ const url = this.connectionUrl();
194
+ if (this.token) {
195
+ this.socket = factory(url.toString());
196
+ }
197
+ else {
198
+ this.socket = factory(url.toString(), {
199
+ headers: { Authorization: this.apiKey },
200
+ });
201
+ }
202
+ this.socket.binaryType = "arraybuffer";
203
+ this.socket.onopen = () => {
204
+ if (this.endUtteranceSilenceThreshold === undefined ||
205
+ this.endUtteranceSilenceThreshold === null) {
206
+ return;
207
+ }
208
+ this.configureEndUtteranceSilenceThreshold(this.endUtteranceSilenceThreshold);
209
+ };
210
+ this.socket.onclose = ({ code, reason }) => {
211
+ if (!reason) {
212
+ if (code in RealtimeErrorType) {
213
+ reason = RealtimeErrorMessages[code];
214
+ }
215
+ }
216
+ this.listeners.close?.(code, reason);
217
+ };
218
+ this.socket.onerror = (event) => {
219
+ if (event.error)
220
+ this.listeners.error?.(event.error);
221
+ else
222
+ this.listeners.error?.(new Error(event.message));
223
+ };
224
+ this.socket.onmessage = ({ data }) => {
225
+ const message = JSON.parse(data.toString());
226
+ if ("error" in message) {
227
+ this.listeners.error?.(new RealtimeError(message.error));
228
+ return;
229
+ }
230
+ switch (message.message_type) {
231
+ case "SessionBegins": {
232
+ const openObject = {
233
+ sessionId: message.session_id,
234
+ expiresAt: new Date(message.expires_at),
235
+ };
236
+ resolve(openObject);
237
+ this.listeners.open?.(openObject);
238
+ break;
239
+ }
240
+ case "PartialTranscript": {
241
+ // message.created is actually a string when coming from the socket
242
+ message.created = new Date(message.created);
243
+ this.listeners.transcript?.(message);
244
+ this.listeners["transcript.partial"]?.(message);
245
+ break;
246
+ }
247
+ case "FinalTranscript": {
248
+ // message.created is actually a string when coming from the socket
249
+ message.created = new Date(message.created);
250
+ this.listeners.transcript?.(message);
251
+ this.listeners["transcript.final"]?.(message);
252
+ break;
253
+ }
254
+ case "SessionInformation": {
255
+ this.listeners.session_information?.(message);
256
+ break;
257
+ }
258
+ case "SessionTerminated": {
259
+ this.sessionTerminatedResolve?.();
260
+ break;
261
+ }
262
+ }
263
+ };
264
+ });
265
+ }
266
+ sendAudio(audio) {
267
+ this.send(audio);
268
+ }
269
+ stream() {
270
+ return new WritableStream({
271
+ write: (chunk) => {
272
+ this.sendAudio(chunk);
273
+ },
274
+ });
275
+ }
276
+ /**
277
+ * Manually end an utterance
278
+ */
279
+ forceEndUtterance() {
280
+ this.send(forceEndOfUtteranceMessage);
281
+ }
282
+ /**
283
+ * Configure the threshold for how long to wait before ending an utterance. Default is 700ms.
284
+ * @param threshold - The duration of the end utterance silence threshold in milliseconds.
285
+ * This value must be an integer between 0 and 20_000.
286
+ */
287
+ configureEndUtteranceSilenceThreshold(threshold) {
288
+ this.send(`{"end_utterance_silence_threshold":${threshold}}`);
289
+ }
290
+ send(data) {
291
+ if (!this.socket || this.socket.readyState !== this.socket.OPEN) {
292
+ throw new Error("Socket is not open for communication");
293
+ }
294
+ this.socket.send(data);
295
+ }
296
+ async close(waitForSessionTermination = true) {
297
+ if (this.socket) {
298
+ if (this.socket.readyState === this.socket.OPEN) {
299
+ if (waitForSessionTermination) {
300
+ const sessionTerminatedPromise = new Promise((resolve) => {
301
+ this.sessionTerminatedResolve = resolve;
302
+ });
303
+ this.socket.send(terminateSessionMessage);
304
+ await sessionTerminatedPromise;
305
+ }
306
+ else {
307
+ this.socket.send(terminateSessionMessage);
308
+ }
309
+ }
310
+ if (this.socket?.removeAllListeners)
311
+ this.socket.removeAllListeners();
312
+ this.socket.close();
313
+ }
314
+ this.listeners = {};
315
+ this.socket = undefined;
316
+ }
317
+ }
318
+ /**
319
+ * @deprecated Use RealtimeTranscriber instead
320
+ */
321
+ class RealtimeService extends RealtimeTranscriber {
322
+ }
323
+
324
+ class RealtimeTranscriberFactory extends BaseService {
325
+ constructor(params) {
326
+ super(params);
327
+ this.rtFactoryParams = params;
328
+ }
329
+ /**
330
+ * @deprecated Use transcriber(...) instead
331
+ */
332
+ createService(params) {
333
+ return this.transcriber(params);
334
+ }
335
+ transcriber(params) {
336
+ const serviceParams = { ...params };
337
+ if (!serviceParams.token && !serviceParams.apiKey) {
338
+ serviceParams.apiKey = this.rtFactoryParams.apiKey;
339
+ }
340
+ return new RealtimeTranscriber(serviceParams);
341
+ }
342
+ async createTemporaryToken(params) {
343
+ const data = await this.fetchJson("/v2/realtime/token", {
344
+ method: "POST",
345
+ body: JSON.stringify(params),
346
+ });
347
+ return data.token;
348
+ }
349
+ }
350
+ /**
351
+ * @deprecated Use RealtimeTranscriberFactory instead
352
+ */
353
+ class RealtimeServiceFactory extends RealtimeTranscriberFactory {
354
+ }
355
+
356
+ function getPath(path) {
357
+ if (path.startsWith("http"))
358
+ return null;
359
+ if (path.startsWith("https"))
360
+ return null;
361
+ if (path.startsWith("data:"))
362
+ return null;
363
+ if (path.startsWith("file://"))
364
+ return path.substring(7);
365
+ if (path.startsWith("file:"))
366
+ return path.substring(5);
367
+ return path;
368
+ }
369
+
370
+ class TranscriptService extends BaseService {
371
+ constructor(params, files) {
372
+ super(params);
373
+ this.files = files;
374
+ }
375
+ /**
376
+ * Transcribe an audio file. This will create a transcript and wait until the transcript status is "completed" or "error".
377
+ * @param params - The parameters to transcribe an audio file.
378
+ * @param options - The options to transcribe an audio file.
379
+ * @returns A promise that resolves to the transcript. The transcript status is "completed" or "error".
380
+ */
381
+ async transcribe(params, options) {
382
+ deprecateConformer2(params);
383
+ const transcript = await this.submit(params);
384
+ return await this.waitUntilReady(transcript.id, options);
385
+ }
386
+ /**
387
+ * Submits a transcription job for an audio file. This will not wait until the transcript status is "completed" or "error".
388
+ * @param params - The parameters to start the transcription of an audio file.
389
+ * @returns A promise that resolves to the queued transcript.
390
+ */
391
+ async submit(params) {
392
+ deprecateConformer2(params);
393
+ let audioUrl;
394
+ let transcriptParams = undefined;
395
+ if ("audio" in params) {
396
+ const { audio, ...audioTranscriptParams } = params;
397
+ if (typeof audio === "string") {
398
+ const path = getPath(audio);
399
+ if (path !== null) {
400
+ // audio is local path, upload local file
401
+ audioUrl = await this.files.upload(path);
402
+ }
403
+ else {
404
+ if (audio.startsWith("data:")) {
405
+ audioUrl = await this.files.upload(audio);
406
+ }
407
+ else {
408
+ // audio is not a local path, and not a data-URI, assume it's a normal URL
409
+ audioUrl = audio;
410
+ }
411
+ }
412
+ }
413
+ else {
414
+ // audio is of uploadable type
415
+ audioUrl = await this.files.upload(audio);
416
+ }
417
+ transcriptParams = { ...audioTranscriptParams, audio_url: audioUrl };
418
+ }
419
+ else {
420
+ transcriptParams = params;
421
+ }
422
+ const data = await this.fetchJson("/v2/transcript", {
423
+ method: "POST",
424
+ body: JSON.stringify(transcriptParams),
425
+ });
426
+ return data;
427
+ }
428
+ /**
429
+ * Create a transcript.
430
+ * @param params - The parameters to create a transcript.
431
+ * @param options - The options used for creating the new transcript.
432
+ * @returns A promise that resolves to the transcript.
433
+ * @deprecated Use `transcribe` instead to transcribe a audio file that includes polling, or `submit` to transcribe a audio file without polling.
434
+ */
435
+ async create(params, options) {
436
+ deprecateConformer2(params);
437
+ const path = getPath(params.audio_url);
438
+ if (path !== null) {
439
+ const uploadUrl = await this.files.upload(path);
440
+ params.audio_url = uploadUrl;
441
+ }
442
+ const data = await this.fetchJson("/v2/transcript", {
443
+ method: "POST",
444
+ body: JSON.stringify(params),
445
+ });
446
+ if (options?.poll ?? true) {
447
+ return await this.waitUntilReady(data.id, options);
448
+ }
449
+ return data;
450
+ }
451
+ /**
452
+ * Wait until the transcript ready, either the status is "completed" or "error".
453
+ * @param transcriptId - The ID of the transcript.
454
+ * @param options - The options to wait until the transcript is ready.
455
+ * @returns A promise that resolves to the transcript. The transcript status is "completed" or "error".
456
+ */
457
+ async waitUntilReady(transcriptId, options) {
458
+ const pollingInterval = options?.pollingInterval ?? 3_000;
459
+ const pollingTimeout = options?.pollingTimeout ?? -1;
460
+ const startTime = Date.now();
461
+ // eslint-disable-next-line no-constant-condition
462
+ while (true) {
463
+ const transcript = await this.get(transcriptId);
464
+ if (transcript.status === "completed" || transcript.status === "error") {
465
+ return transcript;
466
+ }
467
+ else if (pollingTimeout > 0 &&
468
+ Date.now() - startTime > pollingTimeout) {
469
+ throw new Error("Polling timeout");
470
+ }
471
+ else {
472
+ await new Promise((resolve) => setTimeout(resolve, pollingInterval));
473
+ }
474
+ }
475
+ }
476
+ /**
477
+ * Retrieve a transcript.
478
+ * @param id - The identifier of the transcript.
479
+ * @returns A promise that resolves to the transcript.
480
+ */
481
+ get(id) {
482
+ return this.fetchJson(`/v2/transcript/${id}`);
483
+ }
484
+ /**
485
+ * Retrieves a page of transcript listings.
486
+ * @param params - The parameters to filter the transcript list by, or the URL to retrieve the transcript list from.
487
+ */
488
+ async list(params) {
489
+ let url = "/v2/transcript";
490
+ if (typeof params === "string") {
491
+ url = params;
492
+ }
493
+ else if (params) {
494
+ url = `${url}?${new URLSearchParams(Object.keys(params).map((key) => [
495
+ key,
496
+ params[key]?.toString() || "",
497
+ ]))}`;
498
+ }
499
+ const data = await this.fetchJson(url);
500
+ for (const transcriptListItem of data.transcripts) {
501
+ transcriptListItem.created = new Date(transcriptListItem.created);
502
+ if (transcriptListItem.completed) {
503
+ transcriptListItem.completed = new Date(transcriptListItem.completed);
504
+ }
505
+ }
506
+ return data;
507
+ }
508
+ /**
509
+ * Delete a transcript
510
+ * @param id - The identifier of the transcript.
511
+ * @returns A promise that resolves to the transcript.
512
+ */
513
+ delete(id) {
514
+ return this.fetchJson(`/v2/transcript/${id}`, { method: "DELETE" });
515
+ }
516
+ /**
517
+ * Search through the transcript for a specific set of keywords.
518
+ * You can search for individual words, numbers, or phrases containing up to five words or numbers.
519
+ * @param id - The identifier of the transcript.
520
+ * @param words - Keywords to search for.
521
+ * @returns A promise that resolves to the sentences.
522
+ */
523
+ wordSearch(id, words) {
524
+ const params = new URLSearchParams({ words: words.join(",") });
525
+ return this.fetchJson(`/v2/transcript/${id}/word-search?${params.toString()}`);
526
+ }
527
+ /**
528
+ * Retrieve all sentences of a transcript.
529
+ * @param id - The identifier of the transcript.
530
+ * @returns A promise that resolves to the sentences.
531
+ */
532
+ sentences(id) {
533
+ return this.fetchJson(`/v2/transcript/${id}/sentences`);
534
+ }
535
+ /**
536
+ * Retrieve all paragraphs of a transcript.
537
+ * @param id - The identifier of the transcript.
538
+ * @returns A promise that resolves to the paragraphs.
539
+ */
540
+ paragraphs(id) {
541
+ return this.fetchJson(`/v2/transcript/${id}/paragraphs`);
542
+ }
543
+ /**
544
+ * Retrieve subtitles of a transcript.
545
+ * @param id - The identifier of the transcript.
546
+ * @param format - The format of the subtitles.
547
+ * @param chars_per_caption - The maximum number of characters per caption.
548
+ * @returns A promise that resolves to the subtitles text.
549
+ */
550
+ async subtitles(id, format = "srt", chars_per_caption) {
551
+ let url = `/v2/transcript/${id}/${format}`;
552
+ if (chars_per_caption) {
553
+ const params = new URLSearchParams();
554
+ params.set("chars_per_caption", chars_per_caption.toString());
555
+ url += `?${params.toString()}`;
556
+ }
557
+ const response = await this.fetch(url);
558
+ return await response.text();
559
+ }
560
+ /**
561
+ * Retrieve redactions of a transcript.
562
+ * @param id - The identifier of the transcript.
563
+ * @returns A promise that resolves to the subtitles text.
564
+ */
565
+ redactions(id) {
566
+ return this.fetchJson(`/v2/transcript/${id}/redacted-audio`);
567
+ }
568
+ }
569
+ function deprecateConformer2(params) {
570
+ if (!params)
571
+ return;
572
+ if (params.speech_model === "conformer-2") {
573
+ console.warn("The speech_model conformer-2 option is deprecated and will stop working in the near future. Use best or nano instead.");
574
+ }
575
+ }
576
+
577
+ const readFile = async function (
578
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
579
+ path) {
580
+ throw new Error("Interacting with the file system is not supported in this environment.");
581
+ };
582
+
583
+ class FileService extends BaseService {
584
+ /**
585
+ * Upload a local file to AssemblyAI.
586
+ * @param input - The local file path to upload, or a stream or buffer of the file to upload.
587
+ * @returns A promise that resolves to the uploaded file URL.
588
+ */
589
+ async upload(input) {
590
+ let fileData;
591
+ if (typeof input === "string") {
592
+ if (input.startsWith("data:")) {
593
+ fileData = dataUrlToBlob(input);
594
+ }
595
+ else {
596
+ fileData = await readFile();
597
+ }
598
+ }
599
+ else
600
+ fileData = input;
601
+ const data = await this.fetchJson("/v2/upload", {
602
+ method: "POST",
603
+ body: fileData,
604
+ headers: {
605
+ "Content-Type": "application/octet-stream",
606
+ },
607
+ duplex: "half",
608
+ });
609
+ return data.upload_url;
610
+ }
611
+ }
612
+ function dataUrlToBlob(dataUrl) {
613
+ const arr = dataUrl.split(",");
614
+ const mime = arr[0].match(/:(.*?);/)[1];
615
+ const bstr = atob(arr[1]);
616
+ let n = bstr.length;
617
+ const u8arr = new Uint8Array(n);
618
+ while (n--) {
619
+ u8arr[n] = bstr.charCodeAt(n);
620
+ }
621
+ return new Blob([u8arr], { type: mime });
622
+ }
623
+
624
+ const defaultBaseUrl = "https://api.assemblyai.com";
625
+ class AssemblyAI {
626
+ /**
627
+ * Create a new AssemblyAI client.
628
+ * @param params - The parameters for the service, including the API key and base URL, if any.
629
+ */
630
+ constructor(params) {
631
+ params.baseUrl = params.baseUrl || defaultBaseUrl;
632
+ if (params.baseUrl && params.baseUrl.endsWith("/"))
633
+ params.baseUrl = params.baseUrl.slice(0, -1);
634
+ this.files = new FileService(params);
635
+ this.transcripts = new TranscriptService(params, this.files);
636
+ this.lemur = new LemurService(params);
637
+ this.realtime = new RealtimeTranscriberFactory(params);
638
+ }
639
+ }
640
+
641
+ exports.AssemblyAI = AssemblyAI;
642
+ exports.FileService = FileService;
643
+ exports.LemurService = LemurService;
644
+ exports.RealtimeService = RealtimeService;
645
+ exports.RealtimeServiceFactory = RealtimeServiceFactory;
646
+ exports.RealtimeTranscriber = RealtimeTranscriber;
647
+ exports.RealtimeTranscriberFactory = RealtimeTranscriberFactory;
648
+ exports.TranscriptService = TranscriptService;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "assemblyai",
3
- "version": "4.4.2-beta.0",
3
+ "version": "4.4.2-beta.2",
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"
@@ -17,8 +17,16 @@
17
17
  "default": "./dist/deno.mjs"
18
18
  },
19
19
  "workerd": "./dist/index.mjs",
20
- "browser": "./dist/browser.mjs",
21
- "react-native": "./dist/browser.mjs",
20
+ "browser": {
21
+ "types": "./dist/index.d.ts",
22
+ "import": "./dist/browser.mjs",
23
+ "require": "./dist/browser.cjs"
24
+ },
25
+ "react-native": {
26
+ "types": "./dist/index.d.ts",
27
+ "import": "./dist/browser.mjs",
28
+ "require": "./dist/browser.cjs"
29
+ },
22
30
  "node": {
23
31
  "types": "./dist/index.d.ts",
24
32
  "import": "./dist/node.mjs",
@@ -28,6 +36,18 @@
28
36
  "require": "./dist/index.cjs",
29
37
  "default": "./dist/index.cjs"
30
38
  },
39
+ "./browser": {
40
+ "types": "./dist/index.d.ts",
41
+ "import": "./dist/browser.mjs",
42
+ "require": "./dist/browser.cjs",
43
+ "default": "./dist/browser.cjs"
44
+ },
45
+ "./react-native": {
46
+ "types": "./dist/index.d.ts",
47
+ "import": "./dist/browser.mjs",
48
+ "require": "./dist/browser.cjs",
49
+ "default": "./dist/browser.cjs"
50
+ },
31
51
  "./package.json": "./package.json"
32
52
  },
33
53
  "imports": {
@@ -51,6 +71,7 @@
51
71
  "main": "./dist/index.cjs",
52
72
  "require": "./dist/index.cjs",
53
73
  "module": "./dist/index.mjs",
74
+ "react-native": "./dist/index.mjs",
54
75
  "types": "./dist/index.d.ts",
55
76
  "typings": "./dist/index.d.ts",
56
77
  "repository": {
@@ -131,4 +152,4 @@
131
152
  "dependencies": {
132
153
  "ws": "^8.16.0"
133
154
  }
134
- }
155
+ }