assemblyai 4.0.0-beta.0 → 4.0.0-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.
package/dist/deno.mjs ADDED
@@ -0,0 +1,540 @@
1
+ import { WritableStream } from '@swimburger/isomorphic-streams';
2
+ import WebSocket from 'isomorphic-ws';
3
+
4
+ /**
5
+ * Base class for services that communicate with the API.
6
+ */
7
+ class BaseService {
8
+ /**
9
+ * Create a new service.
10
+ * @param params The parameters to use for the service.
11
+ */
12
+ constructor(params) {
13
+ this.params = params;
14
+ }
15
+ async fetch(input, init) {
16
+ init = init ?? {};
17
+ init.headers = init.headers ?? {};
18
+ init.headers = {
19
+ Authorization: this.params.apiKey,
20
+ "Content-Type": "application/json",
21
+ ...init.headers,
22
+ };
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
+ var RealtimeErrorType;
87
+ (function (RealtimeErrorType) {
88
+ RealtimeErrorType[RealtimeErrorType["BadSampleRate"] = 4000] = "BadSampleRate";
89
+ RealtimeErrorType[RealtimeErrorType["AuthFailed"] = 4001] = "AuthFailed";
90
+ // Both InsufficientFunds and FreeAccount error use 4002
91
+ RealtimeErrorType[RealtimeErrorType["InsufficientFundsOrFreeAccount"] = 4002] = "InsufficientFundsOrFreeAccount";
92
+ RealtimeErrorType[RealtimeErrorType["NonexistentSessionId"] = 4004] = "NonexistentSessionId";
93
+ RealtimeErrorType[RealtimeErrorType["SessionExpired"] = 4008] = "SessionExpired";
94
+ RealtimeErrorType[RealtimeErrorType["ClosedSession"] = 4010] = "ClosedSession";
95
+ RealtimeErrorType[RealtimeErrorType["RateLimited"] = 4029] = "RateLimited";
96
+ RealtimeErrorType[RealtimeErrorType["UniqueSessionViolation"] = 4030] = "UniqueSessionViolation";
97
+ RealtimeErrorType[RealtimeErrorType["SessionTimeout"] = 4031] = "SessionTimeout";
98
+ RealtimeErrorType[RealtimeErrorType["AudioTooShort"] = 4032] = "AudioTooShort";
99
+ RealtimeErrorType[RealtimeErrorType["AudioTooLong"] = 4033] = "AudioTooLong";
100
+ RealtimeErrorType[RealtimeErrorType["BadJson"] = 4100] = "BadJson";
101
+ RealtimeErrorType[RealtimeErrorType["BadSchema"] = 4101] = "BadSchema";
102
+ RealtimeErrorType[RealtimeErrorType["TooManyStreams"] = 4102] = "TooManyStreams";
103
+ RealtimeErrorType[RealtimeErrorType["Reconnected"] = 4103] = "Reconnected";
104
+ RealtimeErrorType[RealtimeErrorType["ReconnectAttemptsExhausted"] = 1013] = "ReconnectAttemptsExhausted";
105
+ })(RealtimeErrorType || (RealtimeErrorType = {}));
106
+ const RealtimeErrorMessages = {
107
+ [RealtimeErrorType.BadSampleRate]: "Sample rate must be a positive integer",
108
+ [RealtimeErrorType.AuthFailed]: "Not Authorized",
109
+ [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.",
110
+ [RealtimeErrorType.NonexistentSessionId]: "Session ID does not exist",
111
+ [RealtimeErrorType.SessionExpired]: "Session has expired",
112
+ [RealtimeErrorType.ClosedSession]: "Session is closed",
113
+ [RealtimeErrorType.RateLimited]: "Rate limited",
114
+ [RealtimeErrorType.UniqueSessionViolation]: "Unique session violation",
115
+ [RealtimeErrorType.SessionTimeout]: "Session Timeout",
116
+ [RealtimeErrorType.AudioTooShort]: "Audio too short",
117
+ [RealtimeErrorType.AudioTooLong]: "Audio too long",
118
+ [RealtimeErrorType.BadJson]: "Bad JSON",
119
+ [RealtimeErrorType.BadSchema]: "Bad schema",
120
+ [RealtimeErrorType.TooManyStreams]: "Too many streams",
121
+ [RealtimeErrorType.Reconnected]: "Reconnected",
122
+ [RealtimeErrorType.ReconnectAttemptsExhausted]: "Reconnect attempts exhausted",
123
+ };
124
+ class RealtimeError extends Error {
125
+ }
126
+
127
+ const defaultRealtimeUrl = "wss://api.assemblyai.com/v2/realtime/ws";
128
+ class RealtimeService {
129
+ constructor(params) {
130
+ this.listeners = {};
131
+ this.realtimeUrl = params.realtimeUrl ?? defaultRealtimeUrl;
132
+ this.sampleRate = params.sampleRate ?? 16000;
133
+ this.wordBoost = params.wordBoost;
134
+ if ("apiKey" in params && params.apiKey)
135
+ this.apiKey = params.apiKey;
136
+ if ("token" in params && params.token)
137
+ this.token = params.token;
138
+ if (!(this.apiKey || this.token)) {
139
+ throw new Error("API key or temporary token is required.");
140
+ }
141
+ }
142
+ connectionUrl() {
143
+ const url = new URL(this.realtimeUrl);
144
+ if (url.protocol !== "wss:") {
145
+ throw new Error("Invalid protocol, must be wss");
146
+ }
147
+ const searchParams = new URLSearchParams();
148
+ if (this.token) {
149
+ searchParams.set("token", this.token);
150
+ }
151
+ searchParams.set("sample_rate", this.sampleRate.toString());
152
+ if (this.wordBoost && this.wordBoost.length > 0) {
153
+ searchParams.set("word_boost", JSON.stringify(this.wordBoost));
154
+ }
155
+ url.search = searchParams.toString();
156
+ return url;
157
+ }
158
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
159
+ on(event, listener) {
160
+ this.listeners[event] = listener;
161
+ }
162
+ connect() {
163
+ return new Promise((resolve) => {
164
+ if (this.socket) {
165
+ throw new Error("Already connected");
166
+ }
167
+ const url = this.connectionUrl();
168
+ if (this.token) {
169
+ this.socket = new WebSocket(url.toString());
170
+ }
171
+ else {
172
+ this.socket = new WebSocket(url.toString(), {
173
+ headers: { Authorization: this.apiKey },
174
+ });
175
+ }
176
+ this.socket.onclose = ({ code, reason }) => {
177
+ if (!reason) {
178
+ if (code in RealtimeErrorType) {
179
+ reason = RealtimeErrorMessages[code];
180
+ }
181
+ }
182
+ this.listeners.close?.(code, reason);
183
+ };
184
+ this.socket.onerror = (event) => {
185
+ if (event.error)
186
+ this.listeners.error?.(event.error);
187
+ else
188
+ this.listeners.error?.(new Error(event.message));
189
+ };
190
+ this.socket.onmessage = ({ data }) => {
191
+ const message = JSON.parse(data.toString());
192
+ if ("error" in message) {
193
+ this.listeners.error?.(new RealtimeError(message.error));
194
+ return;
195
+ }
196
+ switch (message.message_type) {
197
+ case "SessionBegins": {
198
+ const openObject = {
199
+ sessionId: message.session_id,
200
+ expiresAt: new Date(message.expires_at),
201
+ };
202
+ resolve(openObject);
203
+ this.listeners.open?.(openObject);
204
+ break;
205
+ }
206
+ case "PartialTranscript": {
207
+ // message.created is actually a string when coming from the socket
208
+ message.created = new Date(message.created);
209
+ this.listeners.transcript?.(message);
210
+ this.listeners["transcript.partial"]?.(message);
211
+ break;
212
+ }
213
+ case "FinalTranscript": {
214
+ // message.created is actually a string when coming from the socket
215
+ message.created = new Date(message.created);
216
+ this.listeners.transcript?.(message);
217
+ this.listeners["transcript.final"]?.(message);
218
+ break;
219
+ }
220
+ case "SessionTerminated": {
221
+ this.sessionTerminatedResolve?.();
222
+ break;
223
+ }
224
+ }
225
+ };
226
+ });
227
+ }
228
+ sendAudio(audio) {
229
+ if (!this.socket || this.socket.readyState !== WebSocket.OPEN) {
230
+ throw new Error("Socket is not open for communication");
231
+ }
232
+ let audioData;
233
+ if (typeof Buffer !== "undefined") {
234
+ audioData = Buffer.from(audio).toString("base64");
235
+ }
236
+ else {
237
+ // Buffer is not available in the browser by default
238
+ // https://stackoverflow.com/a/42334410/2919731
239
+ audioData = btoa(new Uint8Array(audio).reduce((data, byte) => data + String.fromCharCode(byte), ""));
240
+ }
241
+ const payload = {
242
+ audio_data: audioData,
243
+ };
244
+ this.socket.send(JSON.stringify(payload));
245
+ }
246
+ stream() {
247
+ return new WritableStream({
248
+ write: (chunk) => {
249
+ this.sendAudio(chunk);
250
+ },
251
+ });
252
+ }
253
+ async close(waitForSessionTermination = true) {
254
+ if (this.socket) {
255
+ if (this.socket.readyState === WebSocket.OPEN) {
256
+ const terminateSessionMessage = `{"terminate_session": true}`;
257
+ if (waitForSessionTermination) {
258
+ const sessionTerminatedPromise = new Promise((resolve) => {
259
+ this.sessionTerminatedResolve = resolve;
260
+ });
261
+ this.socket.send(terminateSessionMessage);
262
+ await sessionTerminatedPromise;
263
+ }
264
+ else {
265
+ this.socket.send(terminateSessionMessage);
266
+ }
267
+ }
268
+ if ("removeAllListeners" in this.socket)
269
+ this.socket.removeAllListeners();
270
+ this.socket.close();
271
+ }
272
+ this.listeners = {};
273
+ this.socket = undefined;
274
+ }
275
+ }
276
+
277
+ class RealtimeServiceFactory extends BaseService {
278
+ constructor(params) {
279
+ super(params);
280
+ this.rtFactoryParams = params;
281
+ }
282
+ createService(params) {
283
+ if (!params)
284
+ params = { apiKey: this.rtFactoryParams.apiKey };
285
+ else if (!("token" in params) && !params.apiKey) {
286
+ params.apiKey = this.rtFactoryParams.apiKey;
287
+ }
288
+ return new RealtimeService(params);
289
+ }
290
+ async createTemporaryToken(params) {
291
+ const data = await this.fetchJson("/v2/realtime/token", {
292
+ method: "POST",
293
+ body: JSON.stringify(params),
294
+ });
295
+ return data.token;
296
+ }
297
+ }
298
+
299
+ class TranscriptService extends BaseService {
300
+ constructor(params, files) {
301
+ super(params);
302
+ this.files = files;
303
+ }
304
+ /**
305
+ * Transcribe an audio file. This will create a transcript and wait until the transcript status is "completed" or "error".
306
+ * @param params The parameters to transcribe an audio file.
307
+ * @param options The options to transcribe an audio file.
308
+ * @returns A promise that resolves to the transcript. The transcript status is "completed" or "error".
309
+ */
310
+ async transcribe(params, options) {
311
+ const transcript = await this.submit(params);
312
+ return await this.waitUntilReady(transcript.id, options);
313
+ }
314
+ /**
315
+ * Submits a transcription job for an audio file. This will not wait until the transcript status is "completed" or "error".
316
+ * @param params The parameters to start the transcription of an audio file.
317
+ * @returns A promise that resolves to the queued transcript.
318
+ */
319
+ async submit(params) {
320
+ const { audio, ...createParams } = params;
321
+ let audioUrl;
322
+ if (typeof audio === "string") {
323
+ const path = getPath(audio);
324
+ if (path !== null) {
325
+ // audio is local path, upload local file
326
+ audioUrl = await this.files.upload(path);
327
+ }
328
+ else {
329
+ // audio is not a local path, assume it's a URL
330
+ audioUrl = audio;
331
+ }
332
+ }
333
+ else {
334
+ // audio is of uploadable type
335
+ audioUrl = await this.files.upload(audio);
336
+ }
337
+ const data = await this.fetchJson("/v2/transcript", {
338
+ method: "POST",
339
+ body: JSON.stringify({ ...createParams, audio_url: audioUrl }),
340
+ });
341
+ return data;
342
+ }
343
+ /**
344
+ * Create a transcript.
345
+ * @param params The parameters to create a transcript.
346
+ * @param options The options used for creating the new transcript.
347
+ * @returns A promise that resolves to the transcript.
348
+ * @deprecated Use `transcribe` instead to transcribe a audio file that includes polling, or `submit` to transcribe a audio file without polling.
349
+ */
350
+ async create(params, options) {
351
+ const path = getPath(params.audio_url);
352
+ if (path !== null) {
353
+ const uploadUrl = await this.files.upload(path);
354
+ params.audio_url = uploadUrl;
355
+ }
356
+ const data = await this.fetchJson("/v2/transcript", {
357
+ method: "POST",
358
+ body: JSON.stringify(params),
359
+ });
360
+ if (options?.poll ?? true) {
361
+ return await this.waitUntilReady(data.id, options);
362
+ }
363
+ return data;
364
+ }
365
+ /**
366
+ * Wait until the transcript ready, either the status is "completed" or "error".
367
+ * @param transcriptId The ID of the transcript.
368
+ * @param options The options to wait until the transcript is ready.
369
+ * @returns A promise that resolves to the transcript. The transcript status is "completed" or "error".
370
+ */
371
+ async waitUntilReady(transcriptId, options) {
372
+ const pollingInterval = options?.pollingInterval ?? 3000;
373
+ const pollingTimeout = options?.pollingTimeout ?? -1;
374
+ const startTime = Date.now();
375
+ // eslint-disable-next-line no-constant-condition
376
+ while (true) {
377
+ const transcript = await this.get(transcriptId);
378
+ if (transcript.status === "completed" || transcript.status === "error") {
379
+ return transcript;
380
+ }
381
+ else if (pollingTimeout > 0 &&
382
+ Date.now() - startTime > pollingTimeout) {
383
+ throw new Error("Polling timeout");
384
+ }
385
+ else {
386
+ await new Promise((resolve) => setTimeout(resolve, pollingInterval));
387
+ }
388
+ }
389
+ }
390
+ /**
391
+ * Retrieve a transcript.
392
+ * @param id The identifier of the transcript.
393
+ * @returns A promise that resolves to the transcript.
394
+ */
395
+ get(id) {
396
+ return this.fetchJson(`/v2/transcript/${id}`);
397
+ }
398
+ /**
399
+ * Retrieves a page of transcript listings.
400
+ * @param parameters The parameters to filter the transcript list by, or the URL to retrieve the transcript list from.
401
+ */
402
+ async list(parameters) {
403
+ let url = "/v2/transcript";
404
+ if (typeof parameters === "string") {
405
+ url = parameters;
406
+ }
407
+ else if (parameters) {
408
+ url = `${url}?${new URLSearchParams(Object.keys(parameters).map((key) => [
409
+ key,
410
+ parameters[key]?.toString() || "",
411
+ ]))}`;
412
+ }
413
+ const data = await this.fetchJson(url);
414
+ for (const transcriptListItem of data.transcripts) {
415
+ transcriptListItem.created = new Date(transcriptListItem.created);
416
+ if (transcriptListItem.completed) {
417
+ transcriptListItem.completed = new Date(transcriptListItem.completed);
418
+ }
419
+ }
420
+ return data;
421
+ }
422
+ /**
423
+ * Delete a transcript
424
+ * @param id The identifier of the transcript.
425
+ * @returns A promise that resolves to the transcript.
426
+ */
427
+ delete(id) {
428
+ return this.fetchJson(`/v2/transcript/${id}`, { method: "DELETE" });
429
+ }
430
+ /**
431
+ * Search through the transcript for a specific set of keywords.
432
+ * You can search for individual words, numbers, or phrases containing up to five words or numbers.
433
+ * @param id The identifier of the transcript.
434
+ * @param words Keywords to search for.
435
+ * @return A promise that resolves to the sentences.
436
+ */
437
+ wordSearch(id, words) {
438
+ const params = new URLSearchParams({ words: words.join(",") });
439
+ return this.fetchJson(`/v2/transcript/${id}/word-search?${params.toString()}`);
440
+ }
441
+ /**
442
+ * Retrieve all sentences of a transcript.
443
+ * @param id The identifier of the transcript.
444
+ * @return A promise that resolves to the sentences.
445
+ */
446
+ sentences(id) {
447
+ return this.fetchJson(`/v2/transcript/${id}/sentences`);
448
+ }
449
+ /**
450
+ * Retrieve all paragraphs of a transcript.
451
+ * @param id The identifier of the transcript.
452
+ * @return A promise that resolves to the paragraphs.
453
+ */
454
+ paragraphs(id) {
455
+ return this.fetchJson(`/v2/transcript/${id}/paragraphs`);
456
+ }
457
+ /**
458
+ * Retrieve subtitles of a transcript.
459
+ * @param id The identifier of the transcript.
460
+ * @param format The format of the subtitles.
461
+ * @param chars_per_caption The maximum number of characters per caption.
462
+ * @return A promise that resolves to the subtitles text.
463
+ */
464
+ async subtitles(id, format = "srt", chars_per_caption) {
465
+ let url = `/v2/transcript/${id}/${format}`;
466
+ if (chars_per_caption) {
467
+ const params = new URLSearchParams();
468
+ params.set("chars_per_caption", chars_per_caption.toString());
469
+ url += `?${params.toString()}`;
470
+ }
471
+ const response = await this.fetch(url);
472
+ return await response.text();
473
+ }
474
+ /**
475
+ * Retrieve redactions of a transcript.
476
+ * @param id The identifier of the transcript.
477
+ * @return A promise that resolves to the subtitles text.
478
+ */
479
+ redactions(id) {
480
+ return this.fetchJson(`/v2/transcript/${id}/redacted-audio`);
481
+ }
482
+ }
483
+ function getPath(path) {
484
+ let url;
485
+ try {
486
+ url = new URL(path);
487
+ if (url.protocol === "file:")
488
+ return url.pathname;
489
+ else
490
+ return null;
491
+ }
492
+ catch {
493
+ return path;
494
+ }
495
+ }
496
+
497
+ const readFile = async (path) => (await Deno.open(path)).readable;
498
+
499
+ class FileService extends BaseService {
500
+ /**
501
+ * Upload a local file to AssemblyAI.
502
+ * @param input The local file path to upload, or a stream or buffer of the file to upload.
503
+ * @return A promise that resolves to the uploaded file URL.
504
+ */
505
+ async upload(input) {
506
+ let fileData;
507
+ if (typeof input === "string")
508
+ fileData = await readFile(input);
509
+ else
510
+ fileData = input;
511
+ const data = await this.fetchJson("/v2/upload", {
512
+ method: "POST",
513
+ body: fileData,
514
+ headers: {
515
+ "Content-Type": "application/octet-stream",
516
+ },
517
+ duplex: "half",
518
+ });
519
+ return data.upload_url;
520
+ }
521
+ }
522
+
523
+ const defaultBaseUrl = "https://api.assemblyai.com";
524
+ class AssemblyAI {
525
+ /**
526
+ * Create a new AssemblyAI client.
527
+ * @param params The parameters for the service, including the API key and base URL, if any.
528
+ */
529
+ constructor(params) {
530
+ params.baseUrl = params.baseUrl || defaultBaseUrl;
531
+ if (params.baseUrl && params.baseUrl.endsWith("/"))
532
+ params.baseUrl = params.baseUrl.slice(0, -1);
533
+ this.files = new FileService(params);
534
+ this.transcripts = new TranscriptService(params, this.files);
535
+ this.lemur = new LemurService(params);
536
+ this.realtime = new RealtimeServiceFactory(params);
537
+ }
538
+ }
539
+
540
+ export { AssemblyAI, FileService, LemurService, RealtimeService, RealtimeServiceFactory, TranscriptService };
@@ -0,0 +1 @@
1
+ export declare const readFile: (path: string) => Promise<ReadableStream<Uint8Array>>;
@@ -0,0 +1 @@
1
+ export declare const readFile: (path: string) => Promise<ReadableStream<Uint8Array>>;
@@ -0,0 +1 @@
1
+ export declare const readFile: (path: string) => Promise<ReadableStream<Uint8Array>>;
@@ -0,0 +1 @@
1
+ export declare const readFile: (path: string) => Promise<ReadableStream<Uint8Array>>;
package/dist/index.cjs CHANGED
@@ -2,7 +2,6 @@
2
2
 
3
3
  var isomorphicStreams = require('@swimburger/isomorphic-streams');
4
4
  var WebSocket = require('isomorphic-ws');
5
- var fs = require('fs');
6
5
 
7
6
  /******************************************************************************
8
7
  Copyright (c) Microsoft Corporation.
@@ -180,9 +179,9 @@ class RealtimeService {
180
179
  this.realtimeUrl = (_a = params.realtimeUrl) !== null && _a !== void 0 ? _a : defaultRealtimeUrl;
181
180
  this.sampleRate = (_b = params.sampleRate) !== null && _b !== void 0 ? _b : 16000;
182
181
  this.wordBoost = params.wordBoost;
183
- if ("apiKey" in params)
182
+ if ("apiKey" in params && params.apiKey)
184
183
  this.apiKey = params.apiKey;
185
- if ("token" in params)
184
+ if ("token" in params && params.token)
186
185
  this.token = params.token;
187
186
  if (!(this.apiKey || this.token)) {
188
187
  throw new Error("API key or temporary token is required.");
@@ -567,6 +566,14 @@ function getPath(path) {
567
566
  }
568
567
  }
569
568
 
569
+ const readFile = function (
570
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
571
+ path) {
572
+ return __awaiter(this, void 0, void 0, function* () {
573
+ throw new Error("Interacting with the file system is not supported in this environment.");
574
+ });
575
+ };
576
+
570
577
  class FileService extends BaseService {
571
578
  /**
572
579
  * Upload a local file to AssemblyAI.
@@ -577,7 +584,7 @@ class FileService extends BaseService {
577
584
  return __awaiter(this, void 0, void 0, function* () {
578
585
  let fileData;
579
586
  if (typeof input === "string")
580
- fileData = fs.createReadStream(input);
587
+ fileData = yield readFile();
581
588
  else
582
589
  fileData = input;
583
590
  const data = yield this.fetchJson("/v2/upload", {
package/dist/index.mjs CHANGED
@@ -1,6 +1,5 @@
1
1
  import { WritableStream } from '@swimburger/isomorphic-streams';
2
2
  import WebSocket from 'isomorphic-ws';
3
- import fs from 'fs';
4
3
 
5
4
  /******************************************************************************
6
5
  Copyright (c) Microsoft Corporation.
@@ -178,9 +177,9 @@ class RealtimeService {
178
177
  this.realtimeUrl = (_a = params.realtimeUrl) !== null && _a !== void 0 ? _a : defaultRealtimeUrl;
179
178
  this.sampleRate = (_b = params.sampleRate) !== null && _b !== void 0 ? _b : 16000;
180
179
  this.wordBoost = params.wordBoost;
181
- if ("apiKey" in params)
180
+ if ("apiKey" in params && params.apiKey)
182
181
  this.apiKey = params.apiKey;
183
- if ("token" in params)
182
+ if ("token" in params && params.token)
184
183
  this.token = params.token;
185
184
  if (!(this.apiKey || this.token)) {
186
185
  throw new Error("API key or temporary token is required.");
@@ -565,6 +564,14 @@ function getPath(path) {
565
564
  }
566
565
  }
567
566
 
567
+ const readFile = function (
568
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
569
+ path) {
570
+ return __awaiter(this, void 0, void 0, function* () {
571
+ throw new Error("Interacting with the file system is not supported in this environment.");
572
+ });
573
+ };
574
+
568
575
  class FileService extends BaseService {
569
576
  /**
570
577
  * Upload a local file to AssemblyAI.
@@ -575,7 +582,7 @@ class FileService extends BaseService {
575
582
  return __awaiter(this, void 0, void 0, function* () {
576
583
  let fileData;
577
584
  if (typeof input === "string")
578
- fileData = fs.createReadStream(input);
585
+ fileData = yield readFile();
579
586
  else
580
587
  fileData = input;
581
588
  const data = yield this.fetchJson("/v2/upload", {