@ctchealth/plato-sdk 0.0.19 → 0.0.21

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.
@@ -0,0 +1,809 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.PlatoApiClient = void 0;
4
+ const tslib_1 = require("tslib");
5
+ /**
6
+ * Copyright (c) 2025 ctcHealth. All rights reserved.
7
+ *
8
+ * This file is part of the ctcHealth Plato Platform, a proprietary software system developed by ctcHealth.
9
+ *
10
+ * This source code and all related materials are confidential and proprietary to ctcHealth.
11
+ * Unauthorized access, use, copying, modification, distribution, or disclosure is strictly prohibited
12
+ * and may result in disciplinary action and civil and/or criminal penalties.
13
+ *
14
+ * This software is intended solely for authorized use within ctcHealth and its designated partners.
15
+ *
16
+ * For internal use only.
17
+ */
18
+ const axios_1 = tslib_1.__importDefault(require("axios"));
19
+ const web_1 = tslib_1.__importDefault(require("@vapi-ai/web"));
20
+ const utils_1 = require("./utils");
21
+ const constants_1 = require("./constants");
22
+ class PlatoApiClient {
23
+ config;
24
+ // private static readonly ACTIVE_CALL_STORAGE_KEY = 'plato_active_call';
25
+ http;
26
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
27
+ eventListeners = {};
28
+ callControllerInstance;
29
+ eventsAttached = false;
30
+ // private currentCallId?: string;
31
+ // private receivedAnyTranscript = false;
32
+ // Vapi-native events (events that Vapi SDK supports)
33
+ // Exclude our custom SDK events from this list
34
+ vapiEventNames = [
35
+ 'call-start',
36
+ 'call-end',
37
+ 'speech-start',
38
+ 'speech-end',
39
+ 'error',
40
+ 'message',
41
+ 'volume-level',
42
+ ];
43
+ // All event names including SDK-specific events
44
+ eventNames = [
45
+ 'call-start',
46
+ 'call-end',
47
+ 'speech-start',
48
+ 'speech-end',
49
+ 'error',
50
+ 'message',
51
+ 'volume-level',
52
+ 'call-details-ready',
53
+ 'call-ended-reason',
54
+ ];
55
+ constructor(config) {
56
+ this.config = config;
57
+ if (!config.baseUrl) {
58
+ throw new Error('baseUrl is required');
59
+ }
60
+ if (config.baseUrl.endsWith('/')) {
61
+ config.baseUrl = config.baseUrl.slice(0, -1);
62
+ }
63
+ this.http = axios_1.default.create({
64
+ baseURL: config.baseUrl,
65
+ headers: {
66
+ 'x-client-token': config.jwtToken,
67
+ },
68
+ });
69
+ }
70
+ /**
71
+ * Update the JWT token for all subsequent requests.
72
+ * Useful when the token is refreshed or when switching user context.
73
+ */
74
+ setJwtToken(jwtToken) {
75
+ this.http.defaults.headers.common['x-client-token'] = jwtToken;
76
+ }
77
+ /**
78
+ * Remove the JWT token from subsequent requests.
79
+ */
80
+ clearJwtToken() {
81
+ delete this.http.defaults.headers.common['x-client-token'];
82
+ }
83
+ /**
84
+ * Register a listener for a call event with strict typing.
85
+ * @param event Event name
86
+ * @param listener Listener function
87
+ */
88
+ on(event, listener) {
89
+ if (!this.eventListeners[event]) {
90
+ this.eventListeners[event] = [];
91
+ }
92
+ const listeners = this.eventListeners[event];
93
+ if (listeners) {
94
+ listeners.push(listener);
95
+ }
96
+ if (this.callControllerInstance && !this.eventsAttached) {
97
+ this.attachEvents();
98
+ }
99
+ }
100
+ /**
101
+ * Remove a listener for a call event with strict typing.
102
+ * @param event Event name
103
+ * @param listener Listener function
104
+ */
105
+ off(event, listener) {
106
+ const listeners = this.eventListeners[event];
107
+ if (!listeners)
108
+ return;
109
+ this.eventListeners[event] = listeners.filter(l => l !== listener);
110
+ }
111
+ /**
112
+ * Internal: Attach event listeners and propagate to registered listeners.
113
+ */
114
+ attachEvents() {
115
+ if (this.eventsAttached || !this.callControllerInstance)
116
+ return;
117
+ this.eventsAttached = true;
118
+ const vapi = this.callControllerInstance;
119
+ // Only attach Vapi-native events to the Vapi instance
120
+ this.vapiEventNames.forEach(event => {
121
+ vapi.on(event, (payload) => {
122
+ (this.eventListeners[event] || []).forEach(listener => listener(payload));
123
+ });
124
+ });
125
+ }
126
+ /**
127
+ * Internal: Emit SDK-specific events that are not part of Vapi.
128
+ */
129
+ emit(event, payload) {
130
+ const listeners = this.eventListeners[event];
131
+ if (listeners) {
132
+ listeners.forEach(listener => listener(payload));
133
+ }
134
+ }
135
+ // /**
136
+ // * Store active call state in localStorage for recovery purposes.
137
+ // * @private
138
+ // */
139
+ // private storeCallState(state: ActiveCallState): void {
140
+ // try {
141
+ // localStorage.setItem(PlatoApiClient.ACTIVE_CALL_STORAGE_KEY, JSON.stringify(state));
142
+ // } catch (error) {
143
+ // console.warn('Failed to store call state:', error);
144
+ // }
145
+ // }
146
+ // /**
147
+ // * Retrieve active call state from localStorage.
148
+ // * Validates the stored data and clears it if invalid.
149
+ // * @private
150
+ // * @returns The stored call state or null if not found or invalid
151
+ // */
152
+ // private getStoredCallState(): ActiveCallState | null {
153
+ // try {
154
+ // const stored = localStorage.getItem(PlatoApiClient.ACTIVE_CALL_STORAGE_KEY);
155
+ // if (!stored) {
156
+ // return null;
157
+ // }
158
+ // const parsed = JSON.parse(stored) as ActiveCallState;
159
+ // // Validate required fields
160
+ // if (!parsed.callId || !parsed.externalCallId || !parsed.simulationId || !parsed.startedAt) {
161
+ // this.clearCallState();
162
+ // return null;
163
+ // }
164
+ // return parsed;
165
+ // } catch {
166
+ // return null;
167
+ // }
168
+ // }
169
+ // /**
170
+ // * Clear active call state from localStorage.
171
+ // * @private
172
+ // */
173
+ // private clearCallState(): void {
174
+ // try {
175
+ // localStorage.removeItem(PlatoApiClient.ACTIVE_CALL_STORAGE_KEY);
176
+ // } catch {
177
+ // // ignore
178
+ // }
179
+ // }
180
+ // /**
181
+ // * Check if a stored call is considered abandoned based on age.
182
+ // * Calls older than 5 minutes are considered abandoned.
183
+ // * @private
184
+ // * @param state The call state to check
185
+ // * @returns true if the call is abandoned, false otherwise
186
+ // */
187
+ // private isCallAbandoned(state: ActiveCallState): boolean {
188
+ // const ABANDONMENT_THRESHOLD_MS = 5 * 60 * 1000; // 5 minutes
189
+ // const startedAt = new Date(state.startedAt).getTime();
190
+ // const now = Date.now();
191
+ // const age = now - startedAt;
192
+ // return age > ABANDONMENT_THRESHOLD_MS;
193
+ // }
194
+ // /**
195
+ // * Recover and clean up any abandoned calls from previous sessions.
196
+ // *
197
+ // * This method should be called during application initialization,
198
+ // * typically in ngOnInit() or useEffect(). It detects calls that were
199
+ // * active when the page was last refreshed and notifies the backend
200
+ // * to process them if they're older than 5 minutes.
201
+ // *
202
+ // * The backend endpoint is idempotent, so calling this method multiple
203
+ // * times for the same call is safe.
204
+ // *
205
+ // * @returns Promise<boolean> - true if an abandoned call was recovered and processed
206
+ // *
207
+ // * @example
208
+ // * // In Angular component
209
+ // * async ngOnInit(): Promise<void> {
210
+ // * const recovered = await this.platoClient.recoverAbandonedCall();
211
+ // * if (recovered) {
212
+ // * console.log('Recovered abandoned call from previous session');
213
+ // * }
214
+ // * }
215
+ // *
216
+ // * @example
217
+ // * // In React component
218
+ // * useEffect(() => {
219
+ // * platoClient.recoverAbandonedCall()
220
+ // * .then(recovered => {
221
+ // * if (recovered) {
222
+ // * console.log('Recovered abandoned call');
223
+ // * }
224
+ // * })
225
+ // * .catch(console.error);
226
+ // * }, []);
227
+ // */
228
+ // async recoverAbandonedCall(): Promise<boolean> {
229
+ // try {
230
+ // const storedState = this.getStoredCallState();
231
+ // if (!storedState) {
232
+ // return false;
233
+ // }
234
+ // if (!this.isCallAbandoned(storedState)) {
235
+ // return false;
236
+ // }
237
+ // console.log('Detected abandoned call, notifying backend:', storedState.callId);
238
+ // try {
239
+ // const response = await this.http.post('/api/v1/postcall/call-ended', {
240
+ // callId: storedState.callId,
241
+ // });
242
+ // console.log('Backend notified of abandoned call:', response.data);
243
+ // } catch (error) {
244
+ // console.error('Failed to notify backend of abandoned call:', error);
245
+ // }
246
+ // this.clearCallState();
247
+ // return true;
248
+ // } catch (error) {
249
+ // console.error('Error during call recovery:', error);
250
+ // this.clearCallState();
251
+ // return false;
252
+ // }
253
+ // }
254
+ async createSimulation(createSimulationParams) {
255
+ try {
256
+ const res = await this.http.post('/api/v1/simulation', {
257
+ ...createSimulationParams,
258
+ });
259
+ return {
260
+ simulationId: res.data.simulationId,
261
+ phase: res.data.phase,
262
+ };
263
+ }
264
+ catch (e) {
265
+ // if (axios.isAxiosError(e)) {
266
+ // console.error('Error creating simulation:', e.response?.data.message);
267
+ // }
268
+ throw e;
269
+ }
270
+ }
271
+ async checkSimulationStatus(simulationId) {
272
+ const res = await this.http.get(`/api/v1/simulation/status/${simulationId}`);
273
+ return res.data;
274
+ }
275
+ async getUserSimulations() {
276
+ try {
277
+ const res = await this.http.get('/api/v1/simulation/user/simulations');
278
+ return res.data;
279
+ }
280
+ catch (e) {
281
+ // if (axios.isAxiosError(e)) {
282
+ // console.error('Error getting user simulations:', e.response?.data.message);
283
+ // }
284
+ throw e;
285
+ }
286
+ }
287
+ async getSimulationDetails(simulationId) {
288
+ try {
289
+ const res = await this.http.get(`/api/v1/simulation/details/${simulationId}`);
290
+ return res.data;
291
+ }
292
+ catch (e) {
293
+ // if (axios.isAxiosError(e)) {
294
+ // console.error('Error getting simulation details:', e.response?.data.message);
295
+ // }
296
+ throw e;
297
+ }
298
+ }
299
+ /**
300
+ * Deletes a simulation (assistant) from the server and Vapi.
301
+ * @param simulationId - MongoDB ObjectId of the simulation
302
+ * @throws 404 if simulation not found
303
+ */
304
+ async deleteSimulation(simulationId) {
305
+ try {
306
+ await this.http.delete(`/api/v1/simulation/${simulationId}`);
307
+ }
308
+ catch (e) {
309
+ // if (axios.isAxiosError(e)) {
310
+ // console.error('Error deleting simulation:', e.response?.data.message);
311
+ // }
312
+ throw e;
313
+ }
314
+ }
315
+ async getCallDetails(callId) {
316
+ try {
317
+ const res = await this.http.get(`/api/v1/simulation/call/${callId}`);
318
+ return res.data;
319
+ }
320
+ catch (e) {
321
+ // if (axios.isAxiosError(e)) {
322
+ // console.error('Error getting call details:', e.response?.data.message);
323
+ // }
324
+ throw e;
325
+ }
326
+ }
327
+ async getCallRecordings(queryParams) {
328
+ try {
329
+ const res = await this.http.get(`/api/v1/simulation/call/recordings`, {
330
+ params: queryParams,
331
+ });
332
+ return res.data;
333
+ }
334
+ catch (e) {
335
+ // if (axios.isAxiosError(e)) {
336
+ // console.error('Error getting call recordings:', e.response?.data.message);
337
+ // }
338
+ throw e;
339
+ }
340
+ }
341
+ async getCallRecording(callId) {
342
+ try {
343
+ const res = await this.http.get(`/api/v1/simulation/call/recordings/${callId}`);
344
+ return res.data;
345
+ }
346
+ catch (e) {
347
+ // if (axios.isAxiosError(e)) {
348
+ // console.error('Error getting call recording:', e.response?.data.message);
349
+ // }
350
+ throw e;
351
+ }
352
+ }
353
+ /**
354
+ * Remove all listeners for all call events.
355
+ */
356
+ removeAllEventListeners() {
357
+ if (!this.callControllerInstance)
358
+ return;
359
+ this.eventNames.forEach(event => {
360
+ (this.eventListeners[event] || []).forEach(listener => {
361
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
362
+ // @ts-expect-error
363
+ this.callControllerInstance?.off(event, listener);
364
+ });
365
+ this.eventListeners[event] = [];
366
+ });
367
+ this.eventsAttached = false;
368
+ }
369
+ // async startCall(simulationId: string) {
370
+ // // Check for any previous call state before starting new call
371
+ // // If found, notify backend to ensure it gets processed
372
+ // const storedState = this.getStoredCallState();
373
+ // if (storedState) {
374
+ // try {
375
+ // await this.http.post('/api/v1/postcall/call-ended', {
376
+ // callId: storedState.callId,
377
+ // });
378
+ // } catch {
379
+ // // ignore
380
+ // }
381
+ // }
382
+ //
383
+ // // Now clear the state before starting new call
384
+ // this.clearCallState();
385
+ //
386
+ // this.callControllerInstance = new Vapi(
387
+ // this.config.publicKey,
388
+ // 'https://db41aykk1gw9e.cloudfront.net' // base url
389
+ // );
390
+ // if (!this.eventsAttached) {
391
+ // this.attachEvents();
392
+ // }
393
+ //
394
+ // this.receivedAnyTranscript = false;
395
+ // this.callControllerInstance.on(
396
+ // 'message',
397
+ // (msg: { transcript?: string; type?: string; status?: string; endedReason?: string }) => {
398
+ // if (msg.transcript && msg.transcript.trim().length > 0) {
399
+ // this.receivedAnyTranscript = true;
400
+ // }
401
+ // if (msg.type === 'status-update' && msg.status === 'ended' && msg.endedReason) {
402
+ // const reason = msg.endedReason;
403
+ // const isInactivity = /silence|inactivity/i.test(reason);
404
+ // this.emit('call-ended-reason', { reason, isInactivity });
405
+ // }
406
+ // }
407
+ // );
408
+ //
409
+ // // Internal call-end listener
410
+ // this.callControllerInstance.on('call-end', () => {
411
+ // this.onCallEnded().catch(() => {
412
+ // // ignore
413
+ // });
414
+ // });
415
+ //
416
+ // const { data } = await this.http.get(`/api/v1/simulation/${simulationId}`);
417
+ // const assistantId = data as string;
418
+ //
419
+ // let capturedVapiError: unknown;
420
+ // const vapiErrorCapture = (error: unknown) => {
421
+ // capturedVapiError = error;
422
+ // };
423
+ // this.callControllerInstance.on('error', vapiErrorCapture);
424
+ //
425
+ // let call: Call | null;
426
+ // try {
427
+ // call = await this.callControllerInstance.start(assistantId);
428
+ // } catch (e) {
429
+ // this.callControllerInstance.off('error', vapiErrorCapture);
430
+ // this.callControllerInstance?.stop();
431
+ // this.removeAllEventListeners();
432
+ // this.clearCallState();
433
+ // throw e;
434
+ // }
435
+ //
436
+ // this.callControllerInstance.off('error', vapiErrorCapture);
437
+ //
438
+ // if (!call || !call.assistantId) {
439
+ // this.callControllerInstance?.stop();
440
+ // this.removeAllEventListeners();
441
+ // this.clearCallState();
442
+ // if (isCallConcurrencyError(capturedVapiError)) {
443
+ // throw new CallConcurrencyLimitError();
444
+ // }
445
+ // throw new Error('Cannot start a call, please try again later');
446
+ // }
447
+ // try {
448
+ // const apiCall = await this.createCall({
449
+ // callId: call.id,
450
+ // assistantId: call.assistantId,
451
+ // });
452
+ //
453
+ // this.currentCallId = apiCall._id;
454
+ //
455
+ // this.storeCallState({
456
+ // callId: apiCall._id,
457
+ // externalCallId: call.id,
458
+ // simulationId: simulationId,
459
+ // startedAt: new Date().toISOString(),
460
+ // version: 1,
461
+ // });
462
+ //
463
+ // return {
464
+ // stopCall: () => {
465
+ // this.callControllerInstance?.stop();
466
+ // },
467
+ // callId: apiCall._id,
468
+ // on: <K extends CallEventNames>(event: K, listener: CallEventListener<K>) =>
469
+ // this.on(event, listener),
470
+ // off: <K extends CallEventNames>(event: K, listener: CallEventListener<K>) =>
471
+ // this.off(event, listener),
472
+ // };
473
+ // } catch (e) {
474
+ // this.callControllerInstance?.stop();
475
+ // this.removeAllEventListeners();
476
+ // this.clearCallState();
477
+ // throw e;
478
+ // }
479
+ // }
480
+ /**
481
+ * Starts a call for the given simulation.
482
+ * Polls the backend after call-end until the call is finalized, then emits 'call-details-ready'.
483
+ */
484
+ async startCall(simulationId) {
485
+ this.callControllerInstance = new web_1.default(this.config.publicKey, 'https://db41aykk1gw9e.cloudfront.net');
486
+ if (!this.eventsAttached) {
487
+ this.attachEvents();
488
+ }
489
+ this.callControllerInstance.on('message', (msg) => {
490
+ if (msg.type === 'status-update' && msg.status === 'ended' && msg.endedReason) {
491
+ const reason = msg.endedReason;
492
+ const isInactivity = /silence|inactivity/i.test(reason);
493
+ this.emit('call-ended-reason', { reason, isInactivity });
494
+ }
495
+ });
496
+ let callId;
497
+ let stopPolling;
498
+ this.callControllerInstance.on('call-end', () => {
499
+ if (!callId)
500
+ return;
501
+ const callAge = Date.now() - callStartedAt;
502
+ // console.log(`[PlatoSDK] Call ended. Age: ${callAge}ms (${(callAge / 1000).toFixed(2)}s)`);
503
+ if (callAge < 20000) {
504
+ // Call ended within 20s — return whatever is in the DB without requiring a transcript
505
+ const fetchAndEmit = async () => {
506
+ try {
507
+ // console.log('[PlatoSDK] Early end (<20s) — fetching call details immediately (no transcript check)');
508
+ const { data } = await this.http.get(`/api/v1/simulation/call/${callId}`);
509
+ this.emit('call-details-ready', data);
510
+ }
511
+ catch (e) {
512
+ this.emit('error', e instanceof Error ? e : new Error('Failed to fetch call details'));
513
+ }
514
+ finally {
515
+ this.removeAllEventListeners();
516
+ }
517
+ };
518
+ void fetchAndEmit();
519
+ return;
520
+ }
521
+ let stopped = false;
522
+ let nextPollTimer;
523
+ const poll = async () => {
524
+ if (stopped)
525
+ return;
526
+ try {
527
+ // console.log('[PlatoSDK] Polling for call details (waiting for transcript)...');
528
+ const { data } = await this.http.get(`/api/v1/simulation/call/${callId}`);
529
+ if (data.transcript) {
530
+ stopped = true;
531
+ clearTimeout(globalTimer);
532
+ // console.log('[PlatoSDK] Transcript ready — emitting call-details-ready');
533
+ this.emit('call-details-ready', data);
534
+ this.removeAllEventListeners();
535
+ return;
536
+ }
537
+ }
538
+ catch {
539
+ // ignore transient errors, keep polling
540
+ }
541
+ nextPollTimer = setTimeout(() => void poll(), 3000);
542
+ };
543
+ nextPollTimer = setTimeout(() => void poll(), 3000);
544
+ const globalTimer = setTimeout(() => {
545
+ stopped = true;
546
+ clearTimeout(nextPollTimer);
547
+ this.removeAllEventListeners();
548
+ }, 60000);
549
+ stopPolling = () => {
550
+ stopped = true;
551
+ clearTimeout(nextPollTimer);
552
+ clearTimeout(globalTimer);
553
+ };
554
+ });
555
+ const { data } = await this.http.get(`/api/v1/simulation/${simulationId}`);
556
+ const assistantId = data;
557
+ let capturedVapiError;
558
+ const vapiErrorCapture = (error) => {
559
+ capturedVapiError = error;
560
+ };
561
+ this.callControllerInstance.on('error', vapiErrorCapture);
562
+ const callStartedAt = Date.now();
563
+ // console.log('[PlatoSDK] Call start initiated at:', new Date(callStartedAt).toISOString());
564
+ let call;
565
+ try {
566
+ call = await this.callControllerInstance.start(assistantId);
567
+ }
568
+ catch (e) {
569
+ this.callControllerInstance.off('error', vapiErrorCapture);
570
+ this.callControllerInstance.stop();
571
+ this.removeAllEventListeners();
572
+ throw e;
573
+ }
574
+ this.callControllerInstance.off('error', vapiErrorCapture);
575
+ if (!call || !call.assistantId) {
576
+ this.callControllerInstance.stop();
577
+ this.removeAllEventListeners();
578
+ if ((0, utils_1.isCallConcurrencyError)(capturedVapiError)) {
579
+ throw new utils_1.CallConcurrencyLimitError();
580
+ }
581
+ throw new Error('Cannot start a call, please try again later');
582
+ }
583
+ try {
584
+ const apiCall = await this.createCall({
585
+ callId: call.id,
586
+ assistantId: call.assistantId,
587
+ });
588
+ callId = apiCall._id;
589
+ return {
590
+ stopCall: () => {
591
+ this.callControllerInstance?.stop();
592
+ stopPolling?.();
593
+ },
594
+ callId: apiCall._id,
595
+ on: (event, listener) => this.on(event, listener),
596
+ off: (event, listener) => this.off(event, listener),
597
+ };
598
+ }
599
+ catch (e) {
600
+ this.callControllerInstance?.stop();
601
+ this.removeAllEventListeners();
602
+ throw e;
603
+ }
604
+ }
605
+ // private async onCallEnded(): Promise<void> {
606
+ // let callIdForRetry: string | undefined;
607
+ // try {
608
+ // if (!this.currentCallId) {
609
+ // return;
610
+ // }
611
+ //
612
+ // if (!this.receivedAnyTranscript) {
613
+ // return;
614
+ // }
615
+ //
616
+ // callIdForRetry = this.currentCallId;
617
+ //
618
+ // // First attempt
619
+ // let response = await this.http.post('/api/v1/postcall/call-ended', {
620
+ // callId: callIdForRetry,
621
+ // });
622
+ //
623
+ // // If status is "processing", retry once immediately
624
+ // if (response.data?.status === 'processing') {
625
+ // response = await this.http.post('/api/v1/postcall/call-ended', {
626
+ // callId: callIdForRetry,
627
+ // });
628
+ // }
629
+ //
630
+ // try {
631
+ // const callDetails = await this.getCallDetails(callIdForRetry);
632
+ // this.emit('call-details-ready', callDetails);
633
+ // } catch {
634
+ // // ignore
635
+ // }
636
+ // } catch {
637
+ // // ignore
638
+ // } finally {
639
+ // this.currentCallId = undefined;
640
+ // this.clearCallState();
641
+ // this.removeAllEventListeners();
642
+ // }
643
+ // }
644
+ async createCall(payload) {
645
+ const response = await this.http.post('/api/v1/simulation/call', {
646
+ ...payload,
647
+ });
648
+ return response.data;
649
+ }
650
+ async uploadPdfSlides(file) {
651
+ try {
652
+ const checkResult = (0, utils_1.checkFile)(file, constants_1.MAX_PDF_FILE_SIZE, constants_1.ALLOWED_PDF_MIME_TYPES);
653
+ if (checkResult !== true) {
654
+ throw new Error(checkResult);
655
+ }
656
+ // Check PDF page count before proceeding
657
+ const pageCount = await (0, utils_1.getPdfPageCount)(file);
658
+ if (pageCount > constants_1.MAX_PDF_PAGES) {
659
+ throw new Error(`PDF has ${pageCount} pages, which exceeds the maximum allowed page count of ${constants_1.MAX_PDF_PAGES} pages.`);
660
+ }
661
+ const contentHash = await (0, utils_1.calculateHash)(file);
662
+ const filename = file instanceof File ? file.name : file.filename;
663
+ if (!filename) {
664
+ throw new Error('Invalid input: could not extract filename from the provided file or blob.');
665
+ }
666
+ if (/[^a-zA-Z0-9._ -]/.test(filename)) {
667
+ throw new Error('Filename contains invalid characters. Only English letters, numbers, dots, hyphens, and underscores are allowed.');
668
+ }
669
+ const { presignedPost, pdfId } = (await this.http.post('/api/v1/pdfSlides/request-upload', {
670
+ contentHash,
671
+ filename,
672
+ })).data;
673
+ const formData = new FormData();
674
+ Object.entries(presignedPost.fields).forEach(([key, value]) => {
675
+ formData.append(key, value);
676
+ });
677
+ formData.append('file', file);
678
+ try {
679
+ await axios_1.default.post(presignedPost.url, formData, {
680
+ headers: {
681
+ 'Content-Type': 'multipart/form-data',
682
+ },
683
+ });
684
+ }
685
+ catch (uploadError) {
686
+ // S3 upload failed - clean up the MongoDB record created during request-upload
687
+ try {
688
+ await this.deleteSlideAnalysis(pdfId);
689
+ }
690
+ catch {
691
+ // console.error('Failed to clean up PDF record after upload failure:', deleteError);
692
+ }
693
+ throw uploadError;
694
+ }
695
+ /*
696
+ // replace const { presignedPost, pdfId } with const { presignedPost, objectKey, pdfId }
697
+ // Uncomment this block if you are testing locally without AWS EventBridge
698
+ await this.http.post('/api/v1/pdfSlides/test-event-bridge', {
699
+ s3Name: objectKey,
700
+ });
701
+ */
702
+ return pdfId;
703
+ }
704
+ catch (e) {
705
+ // if (axios.isAxiosError(e)) {
706
+ // console.error('Error uploading PDF slides:', e.response?.data?.message || e.message);
707
+ // } else {
708
+ // console.error(
709
+ // 'Error uploading PDF slides:',
710
+ // e instanceof Error ? e.message : 'Unknown error'
711
+ // );
712
+ // }
713
+ throw e;
714
+ }
715
+ }
716
+ async getRecommendations() {
717
+ try {
718
+ const res = await this.http.get('/api/v1/recommendations');
719
+ return res.data;
720
+ }
721
+ catch (e) {
722
+ // if (axios.isAxiosError(e)) {
723
+ // console.error('Error getting recommendations:', e.response?.data.message);
724
+ // }
725
+ throw e;
726
+ }
727
+ }
728
+ async getSlidesAnalysis(queryParams) {
729
+ try {
730
+ const res = await this.http.get('/api/v1/pdfSlides', {
731
+ params: queryParams,
732
+ });
733
+ return res.data;
734
+ }
735
+ catch (e) {
736
+ // if (axios.isAxiosError(e)) {
737
+ // console.error('Error getting PDF slides analysis:', e.response?.data.message);
738
+ // }
739
+ throw e;
740
+ }
741
+ }
742
+ async getSlideAnalysis(id) {
743
+ try {
744
+ const res = await this.http.get(`/api/v1/pdfSlides/${id}`);
745
+ return res.data;
746
+ }
747
+ catch (e) {
748
+ // if (axios.isAxiosError(e)) {
749
+ // console.error('Error getting PDF slide analysis by ID:', e.response?.data.message);
750
+ // }
751
+ throw e;
752
+ }
753
+ }
754
+ async deleteSlideAnalysis(id) {
755
+ try {
756
+ await this.http.delete(`/api/v1/pdfSlides/${id}`);
757
+ }
758
+ catch (e) {
759
+ // if (axios.isAxiosError(e)) {
760
+ // console.error('Error deleting PDF slide analysis:', e.response?.data.message);
761
+ // }
762
+ throw e;
763
+ }
764
+ }
765
+ async checkPdfStatus(id) {
766
+ try {
767
+ const res = await this.http.get(`/api/v1/pdfSlides/status/${id}`);
768
+ return res.data;
769
+ }
770
+ catch (e) {
771
+ // if (axios.isAxiosError(e)) {
772
+ // console.error('Error checking PDF status:', e.response?.data.message);
773
+ // }
774
+ throw e;
775
+ }
776
+ }
777
+ async getAssistantImages() {
778
+ try {
779
+ const res = await this.http.get('/api/v1/assistant-images');
780
+ return res.data;
781
+ }
782
+ catch (e) {
783
+ // if (axios.isAxiosError(e)) {
784
+ // console.error('Error getting assistant images:', e.response?.data.message);
785
+ // }
786
+ throw e;
787
+ }
788
+ }
789
+ /**
790
+ * Deletes a call and all associated data (messages, recommendations, recording).
791
+ * Only the owner of the call can delete it.
792
+ * @param callId - MongoDB ObjectId of the call
793
+ * @throws 404 if call not found
794
+ * @throws 403 if the caller is not the call owner
795
+ */
796
+ async deleteCall(callId) {
797
+ try {
798
+ await this.http.delete(`/api/v1/simulation/call/${callId}`);
799
+ }
800
+ catch (e) {
801
+ // if (axios.isAxiosError(e)) {
802
+ // console.error('Error deleting call:', e.response?.data.message);
803
+ // }
804
+ throw e;
805
+ }
806
+ }
807
+ }
808
+ exports.PlatoApiClient = PlatoApiClient;
809
+ //# sourceMappingURL=plato-sdk.js.map