fireflies-api 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +64 -0
  3. package/dist/action-items-CC9yUxHY.d.cts +380 -0
  4. package/dist/action-items-CC9yUxHY.d.ts +380 -0
  5. package/dist/cli/index.cjs +3909 -0
  6. package/dist/cli/index.cjs.map +1 -0
  7. package/dist/cli/index.d.cts +2 -0
  8. package/dist/cli/index.d.ts +2 -0
  9. package/dist/cli/index.js +3906 -0
  10. package/dist/cli/index.js.map +1 -0
  11. package/dist/index.cjs +3389 -0
  12. package/dist/index.cjs.map +1 -0
  13. package/dist/index.d.cts +966 -0
  14. package/dist/index.d.ts +966 -0
  15. package/dist/index.js +3344 -0
  16. package/dist/index.js.map +1 -0
  17. package/dist/middleware/express.cjs +2491 -0
  18. package/dist/middleware/express.cjs.map +1 -0
  19. package/dist/middleware/express.d.cts +36 -0
  20. package/dist/middleware/express.d.ts +36 -0
  21. package/dist/middleware/express.js +2489 -0
  22. package/dist/middleware/express.js.map +1 -0
  23. package/dist/middleware/fastify.cjs +2501 -0
  24. package/dist/middleware/fastify.cjs.map +1 -0
  25. package/dist/middleware/fastify.d.cts +66 -0
  26. package/dist/middleware/fastify.d.ts +66 -0
  27. package/dist/middleware/fastify.js +2498 -0
  28. package/dist/middleware/fastify.js.map +1 -0
  29. package/dist/middleware/hono.cjs +2493 -0
  30. package/dist/middleware/hono.cjs.map +1 -0
  31. package/dist/middleware/hono.d.cts +37 -0
  32. package/dist/middleware/hono.d.ts +37 -0
  33. package/dist/middleware/hono.js +2490 -0
  34. package/dist/middleware/hono.js.map +1 -0
  35. package/dist/schemas/index.cjs +307 -0
  36. package/dist/schemas/index.cjs.map +1 -0
  37. package/dist/schemas/index.d.cts +926 -0
  38. package/dist/schemas/index.d.ts +926 -0
  39. package/dist/schemas/index.js +268 -0
  40. package/dist/schemas/index.js.map +1 -0
  41. package/dist/speaker-analytics-Dr46LKyP.d.ts +275 -0
  42. package/dist/speaker-analytics-l45LXqO1.d.cts +275 -0
  43. package/dist/types-BX-3JcRI.d.cts +41 -0
  44. package/dist/types-C_XxdRd1.d.cts +1546 -0
  45. package/dist/types-CaHcwnKw.d.ts +41 -0
  46. package/dist/types-DIPZmUl3.d.ts +1546 -0
  47. package/package.json +126 -0
package/dist/index.js ADDED
@@ -0,0 +1,3344 @@
1
+ import { io } from 'socket.io-client';
2
+ import { createHmac, timingSafeEqual } from 'crypto';
3
+
4
+ // src/errors.ts
5
+ var FirefliesError = class extends Error {
6
+ code = "FIREFLIES_ERROR";
7
+ status;
8
+ constructor(message, options) {
9
+ super(message, { cause: options?.cause });
10
+ this.name = "FirefliesError";
11
+ this.status = options?.status;
12
+ }
13
+ };
14
+ var AuthenticationError = class extends FirefliesError {
15
+ code = "AUTHENTICATION_ERROR";
16
+ constructor(message = "Invalid or missing API key") {
17
+ super(message, { status: 401 });
18
+ this.name = "AuthenticationError";
19
+ }
20
+ };
21
+ var RateLimitError = class extends FirefliesError {
22
+ code = "RATE_LIMIT_ERROR";
23
+ /** Suggested wait time in milliseconds before retrying. */
24
+ retryAfter;
25
+ constructor(message = "Rate limit exceeded", retryAfter) {
26
+ super(message, { status: 429 });
27
+ this.name = "RateLimitError";
28
+ this.retryAfter = retryAfter;
29
+ }
30
+ };
31
+ var NotFoundError = class extends FirefliesError {
32
+ code = "NOT_FOUND";
33
+ constructor(message = "Resource not found") {
34
+ super(message, { status: 404 });
35
+ this.name = "NotFoundError";
36
+ }
37
+ };
38
+ var ValidationError = class extends FirefliesError {
39
+ code = "VALIDATION_ERROR";
40
+ constructor(message) {
41
+ super(message, { status: 400 });
42
+ this.name = "ValidationError";
43
+ }
44
+ };
45
+ var GraphQLError = class extends FirefliesError {
46
+ code = "GRAPHQL_ERROR";
47
+ errors;
48
+ constructor(message, errors) {
49
+ super(message);
50
+ this.name = "GraphQLError";
51
+ this.errors = errors;
52
+ }
53
+ };
54
+ var TimeoutError = class extends FirefliesError {
55
+ code = "TIMEOUT_ERROR";
56
+ constructor(message = "Request timed out") {
57
+ super(message, { status: 408 });
58
+ this.name = "TimeoutError";
59
+ }
60
+ };
61
+ var NetworkError = class extends FirefliesError {
62
+ code = "NETWORK_ERROR";
63
+ constructor(message, cause) {
64
+ super(message, { cause });
65
+ this.name = "NetworkError";
66
+ }
67
+ };
68
+ var RealtimeError = class extends FirefliesError {
69
+ code = "REALTIME_ERROR";
70
+ constructor(message, options) {
71
+ super(message, options);
72
+ this.name = "RealtimeError";
73
+ }
74
+ };
75
+ var ConnectionError = class extends RealtimeError {
76
+ code = "CONNECTION_ERROR";
77
+ constructor(message = "Failed to establish realtime connection", options) {
78
+ super(message, options);
79
+ this.name = "ConnectionError";
80
+ }
81
+ };
82
+ var StreamClosedError = class extends RealtimeError {
83
+ code = "STREAM_CLOSED";
84
+ constructor(message = "Stream has been closed") {
85
+ super(message);
86
+ this.name = "StreamClosedError";
87
+ }
88
+ };
89
+ var WebhookVerificationError = class extends FirefliesError {
90
+ code = "WEBHOOK_VERIFICATION_FAILED";
91
+ constructor(message) {
92
+ super(message, { status: 401 });
93
+ this.name = "WebhookVerificationError";
94
+ }
95
+ };
96
+ var WebhookParseError = class extends FirefliesError {
97
+ code = "WEBHOOK_PARSE_FAILED";
98
+ constructor(message) {
99
+ super(message, { status: 400 });
100
+ this.name = "WebhookParseError";
101
+ }
102
+ };
103
+ var ChunkTimeoutError = class extends RealtimeError {
104
+ code = "CHUNK_TIMEOUT";
105
+ timeoutMs;
106
+ constructor(timeoutMs) {
107
+ super(`No chunks received for ${timeoutMs}ms`);
108
+ this.name = "ChunkTimeoutError";
109
+ this.timeoutMs = timeoutMs;
110
+ }
111
+ };
112
+ function parseErrorResponse(status, body, defaultMessage) {
113
+ const message = extractErrorMessage(body) ?? defaultMessage;
114
+ switch (status) {
115
+ case 401:
116
+ return new AuthenticationError(message);
117
+ case 404:
118
+ return new NotFoundError(message);
119
+ case 429: {
120
+ const retryAfter = extractRetryAfter(body);
121
+ return new RateLimitError(message, retryAfter);
122
+ }
123
+ case 400:
124
+ return new ValidationError(message);
125
+ default:
126
+ return new FirefliesError(message, { status });
127
+ }
128
+ }
129
+ function extractErrorMessage(body) {
130
+ if (typeof body === "object" && body !== null) {
131
+ const obj = body;
132
+ if (typeof obj.message === "string") {
133
+ return obj.message;
134
+ }
135
+ if (typeof obj.error === "string") {
136
+ return obj.error;
137
+ }
138
+ }
139
+ return void 0;
140
+ }
141
+ function extractRetryAfter(body) {
142
+ if (typeof body === "object" && body !== null) {
143
+ const obj = body;
144
+ if (typeof obj.retryAfter === "number") {
145
+ return obj.retryAfter;
146
+ }
147
+ }
148
+ return void 0;
149
+ }
150
+
151
+ // src/utils/rate-limit-tracker.ts
152
+ var RATE_LIMIT_REMAINING_HEADER = "x-ratelimit-remaining-api";
153
+ var RATE_LIMIT_LIMIT_HEADER = "x-ratelimit-limit-api";
154
+ var RATE_LIMIT_RESET_HEADER = "x-ratelimit-reset-api";
155
+ var RateLimitTracker = class {
156
+ _remaining;
157
+ _limit;
158
+ _resetInSeconds;
159
+ _updatedAt;
160
+ warningThreshold;
161
+ /**
162
+ * Create a new RateLimitTracker.
163
+ * @param warningThreshold - Threshold below which isLow returns true
164
+ */
165
+ constructor(warningThreshold = 10) {
166
+ this._remaining = void 0;
167
+ this._limit = void 0;
168
+ this._resetInSeconds = void 0;
169
+ this._updatedAt = 0;
170
+ this.warningThreshold = warningThreshold;
171
+ }
172
+ /**
173
+ * Get the current rate limit state.
174
+ */
175
+ get state() {
176
+ return {
177
+ remaining: this._remaining,
178
+ limit: this._limit,
179
+ resetInSeconds: this._resetInSeconds,
180
+ updatedAt: this._updatedAt
181
+ };
182
+ }
183
+ /**
184
+ * Check if remaining requests are below the warning threshold.
185
+ * Returns false if remaining is undefined (header not received).
186
+ */
187
+ get isLow() {
188
+ return this._remaining !== void 0 && this._remaining < this.warningThreshold;
189
+ }
190
+ /**
191
+ * Update state from response headers.
192
+ * Extracts x-ratelimit-remaining-api, x-ratelimit-limit-api, and x-ratelimit-reset-api headers.
193
+ *
194
+ * @param headers - Response headers (Headers object or plain object)
195
+ */
196
+ update(headers) {
197
+ const remaining = this.getHeader(headers, RATE_LIMIT_REMAINING_HEADER);
198
+ if (remaining !== null) {
199
+ const parsed = Number.parseInt(remaining, 10);
200
+ if (!Number.isNaN(parsed) && parsed >= 0) {
201
+ this._remaining = parsed;
202
+ }
203
+ }
204
+ const limit = this.getHeader(headers, RATE_LIMIT_LIMIT_HEADER);
205
+ if (limit !== null) {
206
+ const parsed = Number.parseInt(limit, 10);
207
+ if (!Number.isNaN(parsed) && parsed >= 0) {
208
+ this._limit = parsed;
209
+ }
210
+ }
211
+ const reset = this.getHeader(headers, RATE_LIMIT_RESET_HEADER);
212
+ if (reset !== null) {
213
+ const parsed = Number.parseInt(reset, 10);
214
+ if (!Number.isNaN(parsed) && parsed >= 0) {
215
+ this._resetInSeconds = parsed;
216
+ }
217
+ }
218
+ this._updatedAt = Date.now();
219
+ }
220
+ /**
221
+ * Reset the tracker to initial state.
222
+ */
223
+ reset() {
224
+ this._remaining = void 0;
225
+ this._limit = void 0;
226
+ this._resetInSeconds = void 0;
227
+ this._updatedAt = 0;
228
+ }
229
+ /**
230
+ * Calculate the delay to apply before the next request.
231
+ * Returns 0 if throttling is disabled or not needed.
232
+ *
233
+ * Uses linear interpolation: more delay as remaining approaches 0.
234
+ * - remaining >= startThreshold: no delay
235
+ * - remaining = 0: maxDelay
236
+ * - remaining in between: proportional delay
237
+ *
238
+ * @param config - Throttle configuration
239
+ * @returns Delay in milliseconds
240
+ */
241
+ getThrottleDelay(config) {
242
+ if (!config?.enabled) {
243
+ return 0;
244
+ }
245
+ if (this._remaining === void 0) {
246
+ return 0;
247
+ }
248
+ const startThreshold = Math.max(1, config.startThreshold ?? 20);
249
+ let minDelay = config.minDelay ?? 100;
250
+ let maxDelay = config.maxDelay ?? 2e3;
251
+ if (minDelay > maxDelay) {
252
+ [minDelay, maxDelay] = [maxDelay, minDelay];
253
+ }
254
+ if (this._remaining >= startThreshold) {
255
+ return 0;
256
+ }
257
+ if (this._remaining <= 0) {
258
+ return maxDelay;
259
+ }
260
+ const ratio = 1 - this._remaining / startThreshold;
261
+ return Math.round(minDelay + ratio * (maxDelay - minDelay));
262
+ }
263
+ /**
264
+ * Extract a header value from Headers object or plain object.
265
+ * For plain objects, performs case-insensitive key lookup.
266
+ */
267
+ getHeader(headers, name) {
268
+ if (headers instanceof Headers) {
269
+ return headers.get(name);
270
+ }
271
+ const lowerName = name.toLowerCase();
272
+ for (const key of Object.keys(headers)) {
273
+ if (key.toLowerCase() === lowerName) {
274
+ return headers[key] ?? null;
275
+ }
276
+ }
277
+ return null;
278
+ }
279
+ };
280
+
281
+ // src/utils/retry.ts
282
+ var DEFAULT_OPTIONS = {
283
+ maxRetries: 3,
284
+ baseDelay: 1e3,
285
+ maxDelay: 3e4
286
+ };
287
+ async function retry(fn, options) {
288
+ const maxRetries = options?.maxRetries ?? DEFAULT_OPTIONS.maxRetries;
289
+ const baseDelay = options?.baseDelay ?? DEFAULT_OPTIONS.baseDelay;
290
+ const maxDelay = options?.maxDelay ?? DEFAULT_OPTIONS.maxDelay;
291
+ const shouldRetry = options?.shouldRetry ?? isRetryableError;
292
+ let lastError;
293
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
294
+ try {
295
+ return await fn();
296
+ } catch (error) {
297
+ lastError = error;
298
+ if (attempt >= maxRetries || !shouldRetry(error, attempt)) {
299
+ throw error;
300
+ }
301
+ const delay4 = calculateDelay(error, attempt, baseDelay, maxDelay);
302
+ await sleep(delay4);
303
+ }
304
+ }
305
+ throw lastError;
306
+ }
307
+ function isRetryableError(error) {
308
+ if (error instanceof RateLimitError) {
309
+ return true;
310
+ }
311
+ if (error instanceof TimeoutError) {
312
+ return true;
313
+ }
314
+ if (error instanceof NetworkError) {
315
+ return true;
316
+ }
317
+ if (error instanceof Error && "status" in error && typeof error.status === "number") {
318
+ return error.status >= 500 && error.status < 600;
319
+ }
320
+ return false;
321
+ }
322
+ function calculateDelay(error, attempt, baseDelay, maxDelay) {
323
+ if (error instanceof RateLimitError && error.retryAfter !== void 0) {
324
+ return Math.min(error.retryAfter, maxDelay);
325
+ }
326
+ const exponentialDelay = baseDelay * 2 ** attempt;
327
+ const jitter = Math.random() * 0.1 * exponentialDelay;
328
+ return Math.min(exponentialDelay + jitter, maxDelay);
329
+ }
330
+ function sleep(ms) {
331
+ return new Promise((resolve) => setTimeout(resolve, ms));
332
+ }
333
+
334
+ // src/graphql/client.ts
335
+ var DEFAULT_BASE_URL = "https://api.fireflies.ai/graphql";
336
+ var DEFAULT_TIMEOUT = 3e4;
337
+ var GraphQLClient = class {
338
+ apiKey;
339
+ baseUrl;
340
+ timeout;
341
+ retryOptions;
342
+ rateLimitTracker;
343
+ rateLimitConfig;
344
+ lastWarningRemaining;
345
+ constructor(config) {
346
+ if (!config.apiKey) {
347
+ throw new FirefliesError("API key is required");
348
+ }
349
+ this.apiKey = config.apiKey;
350
+ this.baseUrl = config.baseUrl ?? DEFAULT_BASE_URL;
351
+ this.timeout = config.timeout ?? DEFAULT_TIMEOUT;
352
+ this.retryOptions = buildRetryOptions(config.retry);
353
+ if (config.rateLimit) {
354
+ const warningThreshold = config.rateLimit.warningThreshold ?? 10;
355
+ this.rateLimitTracker = new RateLimitTracker(warningThreshold);
356
+ this.rateLimitConfig = config.rateLimit;
357
+ } else {
358
+ this.rateLimitTracker = null;
359
+ this.rateLimitConfig = null;
360
+ }
361
+ }
362
+ /**
363
+ * Get the current rate limit state.
364
+ * Returns undefined if rate limit tracking is not configured.
365
+ */
366
+ get rateLimitState() {
367
+ return this.rateLimitTracker?.state;
368
+ }
369
+ /**
370
+ * Execute a GraphQL query or mutation.
371
+ *
372
+ * @param query - GraphQL query string
373
+ * @param variables - Optional query variables
374
+ * @returns The data from the GraphQL response
375
+ * @throws GraphQLError if the response contains errors
376
+ * @throws AuthenticationError if the API key is invalid
377
+ * @throws RateLimitError if rate limits are exceeded
378
+ */
379
+ async execute(query, variables) {
380
+ return retry(() => this.executeOnce(query, variables), this.retryOptions);
381
+ }
382
+ async executeOnce(query, variables) {
383
+ await this.applyThrottleDelay();
384
+ const controller = new AbortController();
385
+ const timeoutId = setTimeout(() => controller.abort(), this.timeout);
386
+ try {
387
+ const response = await fetch(this.baseUrl, {
388
+ method: "POST",
389
+ headers: {
390
+ "Content-Type": "application/json",
391
+ Authorization: `Bearer ${this.apiKey}`
392
+ },
393
+ body: JSON.stringify({ query, variables }),
394
+ signal: controller.signal
395
+ });
396
+ clearTimeout(timeoutId);
397
+ this.updateRateLimitState(response.headers);
398
+ if (!response.ok) {
399
+ const body = await this.safeParseJson(response);
400
+ if (response.status === 429) {
401
+ const retryAfter = this.parseRetryAfter(response.headers);
402
+ this.invokeRateLimitedCallback(retryAfter);
403
+ throw parseErrorResponse(
404
+ response.status,
405
+ body,
406
+ `GraphQL request failed with status ${response.status}`
407
+ );
408
+ }
409
+ throw parseErrorResponse(
410
+ response.status,
411
+ body,
412
+ `GraphQL request failed with status ${response.status}`
413
+ );
414
+ }
415
+ const json = await response.json();
416
+ if (json.errors && json.errors.length > 0) {
417
+ throw this.parseGraphQLErrors(json.errors);
418
+ }
419
+ if (json.data === void 0) {
420
+ throw new FirefliesError("GraphQL response missing data field");
421
+ }
422
+ return json.data;
423
+ } catch (error) {
424
+ clearTimeout(timeoutId);
425
+ if (error instanceof FirefliesError) {
426
+ throw error;
427
+ }
428
+ if (error instanceof Error) {
429
+ if (error.name === "AbortError") {
430
+ throw new TimeoutError(`Request timed out after ${this.timeout}ms`);
431
+ }
432
+ throw new NetworkError(`Network request failed: ${error.message}`, error);
433
+ }
434
+ throw new NetworkError("Unknown network error occurred", error);
435
+ }
436
+ }
437
+ async safeParseJson(response) {
438
+ try {
439
+ return await response.json();
440
+ } catch {
441
+ return null;
442
+ }
443
+ }
444
+ /**
445
+ * Apply throttle delay before request if configured.
446
+ */
447
+ async applyThrottleDelay() {
448
+ if (!this.rateLimitTracker || !this.rateLimitConfig?.throttle) {
449
+ return;
450
+ }
451
+ const delay4 = this.rateLimitTracker.getThrottleDelay(this.rateLimitConfig.throttle);
452
+ if (delay4 > 0) {
453
+ await sleep2(delay4);
454
+ }
455
+ }
456
+ /**
457
+ * Update rate limit state from response headers and invoke callbacks.
458
+ */
459
+ updateRateLimitState(headers) {
460
+ if (!this.rateLimitTracker || !this.rateLimitConfig) {
461
+ return;
462
+ }
463
+ const wasLow = this.rateLimitTracker.isLow;
464
+ this.rateLimitTracker.update(headers);
465
+ const state = this.rateLimitTracker.state;
466
+ this.safeCallback(() => this.rateLimitConfig?.onUpdate?.(state));
467
+ if (this.rateLimitTracker.isLow) {
468
+ const shouldWarn = !wasLow || // Just crossed threshold
469
+ state.remaining !== void 0 && this.lastWarningRemaining !== void 0 && state.remaining < this.lastWarningRemaining;
470
+ if (shouldWarn) {
471
+ this.lastWarningRemaining = state.remaining;
472
+ this.safeCallback(() => this.rateLimitConfig?.onWarning?.(state));
473
+ }
474
+ }
475
+ }
476
+ /**
477
+ * Parse Retry-After header value.
478
+ */
479
+ parseRetryAfter(headers) {
480
+ const value = headers.get("retry-after");
481
+ if (!value) return void 0;
482
+ const parsed = Number.parseInt(value, 10);
483
+ return Number.isNaN(parsed) ? void 0 : parsed;
484
+ }
485
+ /**
486
+ * Invoke the onRateLimited callback.
487
+ */
488
+ invokeRateLimitedCallback(retryAfter) {
489
+ if (!this.rateLimitTracker || !this.rateLimitConfig?.onRateLimited) {
490
+ return;
491
+ }
492
+ const state = this.rateLimitTracker.state;
493
+ this.safeCallback(() => this.rateLimitConfig?.onRateLimited?.(state, retryAfter));
494
+ }
495
+ /**
496
+ * Safely invoke a callback, catching any errors to prevent user code from breaking the SDK.
497
+ */
498
+ safeCallback(fn) {
499
+ try {
500
+ fn();
501
+ } catch {
502
+ }
503
+ }
504
+ parseGraphQLErrors(errors) {
505
+ const firstError = errors[0];
506
+ if (!firstError) {
507
+ return new GraphQLError("Unknown GraphQL error", errors);
508
+ }
509
+ const message = firstError.message;
510
+ if (message.toLowerCase().includes("unauthorized") || message.toLowerCase().includes("authentication")) {
511
+ return parseErrorResponse(401, { message }, message);
512
+ }
513
+ if (message.toLowerCase().includes("not found")) {
514
+ return parseErrorResponse(404, { message }, message);
515
+ }
516
+ return new GraphQLError(message, errors);
517
+ }
518
+ };
519
+ function buildRetryOptions(config) {
520
+ if (!config) {
521
+ return {};
522
+ }
523
+ return {
524
+ maxRetries: config.maxRetries,
525
+ baseDelay: config.baseDelay,
526
+ maxDelay: config.maxDelay
527
+ };
528
+ }
529
+ function sleep2(ms) {
530
+ return new Promise((resolve) => setTimeout(resolve, ms));
531
+ }
532
+
533
+ // src/graphql/mutations/audio.ts
534
+ function createAudioAPI(client) {
535
+ return {
536
+ async upload(params) {
537
+ const mutation = `
538
+ mutation UploadAudio($input: AudioUploadInput!) {
539
+ uploadAudio(input: $input) {
540
+ success
541
+ title
542
+ message
543
+ }
544
+ }
545
+ `;
546
+ const data = await client.execute(mutation, {
547
+ input: params
548
+ });
549
+ return data.uploadAudio;
550
+ }
551
+ };
552
+ }
553
+
554
+ // src/graphql/mutations/transcripts.ts
555
+ function createTranscriptsMutationsAPI(client) {
556
+ return {
557
+ async delete(id) {
558
+ const mutation = `
559
+ mutation deleteTranscript($id: String!) {
560
+ deleteTranscript(id: $id) {
561
+ id
562
+ title
563
+ organizer_email
564
+ date
565
+ duration
566
+ }
567
+ }
568
+ `;
569
+ const data = await client.execute(mutation, { id });
570
+ return data.deleteTranscript;
571
+ }
572
+ };
573
+ }
574
+
575
+ // src/graphql/mutations/users.ts
576
+ function createUsersMutationsAPI(client) {
577
+ return {
578
+ async setRole(userId, role) {
579
+ const mutation = `
580
+ mutation setUserRole($userId: String!, $role: Role!) {
581
+ setUserRole(user_id: $userId, role: $role) {
582
+ id
583
+ name
584
+ email
585
+ role
586
+ }
587
+ }
588
+ `;
589
+ const data = await client.execute(mutation, {
590
+ userId,
591
+ role
592
+ });
593
+ return data.setUserRole;
594
+ }
595
+ };
596
+ }
597
+
598
+ // src/helpers/pagination.ts
599
+ async function* paginate(fetcher, pageSize = 50) {
600
+ let skip = 0;
601
+ let hasMore = true;
602
+ while (hasMore) {
603
+ const page = await fetcher(skip, pageSize);
604
+ for (const item of page) {
605
+ yield item;
606
+ }
607
+ if (page.length < pageSize) {
608
+ hasMore = false;
609
+ } else {
610
+ skip += pageSize;
611
+ }
612
+ }
613
+ }
614
+ async function collectAll(iterable) {
615
+ const items = [];
616
+ for await (const item of iterable) {
617
+ items.push(item);
618
+ }
619
+ return items;
620
+ }
621
+
622
+ // src/graphql/queries/ai-apps.ts
623
+ var AI_APP_OUTPUT_FIELDS = `
624
+ transcript_id
625
+ user_id
626
+ app_id
627
+ created_at
628
+ title
629
+ prompt
630
+ response
631
+ `;
632
+ function createAIAppsAPI(client) {
633
+ return {
634
+ async list(params) {
635
+ const query = `
636
+ query GetAIAppsOutputs(
637
+ $appId: String
638
+ $transcriptId: String
639
+ $skip: Float
640
+ $limit: Float
641
+ ) {
642
+ apps(
643
+ app_id: $appId
644
+ transcript_id: $transcriptId
645
+ skip: $skip
646
+ limit: $limit
647
+ ) {
648
+ outputs { ${AI_APP_OUTPUT_FIELDS} }
649
+ }
650
+ }
651
+ `;
652
+ const data = await client.execute(query, {
653
+ appId: params?.app_id,
654
+ transcriptId: params?.transcript_id,
655
+ skip: params?.skip,
656
+ limit: params?.limit ?? 10
657
+ });
658
+ return data.apps.outputs;
659
+ },
660
+ listAll(params) {
661
+ return paginate((skip, limit) => this.list({ ...params, skip, limit }), 10);
662
+ }
663
+ };
664
+ }
665
+
666
+ // src/graphql/queries/bites.ts
667
+ var BITE_FIELDS = `
668
+ id
669
+ transcript_id
670
+ user_id
671
+ name
672
+ status
673
+ summary
674
+ summary_status
675
+ media_type
676
+ start_time
677
+ end_time
678
+ created_at
679
+ thumbnail
680
+ preview
681
+ captions {
682
+ index
683
+ text
684
+ start_time
685
+ end_time
686
+ speaker_id
687
+ speaker_name
688
+ }
689
+ sources {
690
+ src
691
+ type
692
+ }
693
+ user {
694
+ id
695
+ name
696
+ first_name
697
+ last_name
698
+ picture
699
+ }
700
+ created_from {
701
+ id
702
+ name
703
+ type
704
+ description
705
+ duration
706
+ }
707
+ privacies
708
+ `;
709
+ function createBitesAPI(client) {
710
+ return {
711
+ async get(id) {
712
+ const query = `
713
+ query Bite($biteId: ID!) {
714
+ bite(id: $biteId) { ${BITE_FIELDS} }
715
+ }
716
+ `;
717
+ const data = await client.execute(query, { biteId: id });
718
+ return data.bite;
719
+ },
720
+ async list(params) {
721
+ const query = `
722
+ query Bites(
723
+ $transcriptId: ID
724
+ $mine: Boolean
725
+ $myTeam: Boolean
726
+ $limit: Int
727
+ $skip: Int
728
+ ) {
729
+ bites(
730
+ transcript_id: $transcriptId
731
+ mine: $mine
732
+ my_team: $myTeam
733
+ limit: $limit
734
+ skip: $skip
735
+ ) { ${BITE_FIELDS} }
736
+ }
737
+ `;
738
+ const data = await client.execute(query, {
739
+ transcriptId: params.transcript_id,
740
+ mine: params.mine,
741
+ myTeam: params.my_team,
742
+ limit: params.limit ?? 50,
743
+ skip: params.skip
744
+ });
745
+ return data.bites;
746
+ },
747
+ listAll(params) {
748
+ return paginate((skip, limit) => this.list({ ...params, skip, limit }), 50);
749
+ },
750
+ async create(params) {
751
+ const mutation = `
752
+ mutation CreateBite(
753
+ $transcriptId: ID!
754
+ $startTime: Float!
755
+ $endTime: Float!
756
+ $name: String
757
+ $mediaType: String
758
+ $summary: String
759
+ $privacies: [BitePrivacy!]
760
+ ) {
761
+ createBite(
762
+ transcript_Id: $transcriptId
763
+ start_time: $startTime
764
+ end_time: $endTime
765
+ name: $name
766
+ media_type: $mediaType
767
+ summary: $summary
768
+ privacies: $privacies
769
+ ) {
770
+ id
771
+ name
772
+ status
773
+ summary
774
+ }
775
+ }
776
+ `;
777
+ const data = await client.execute(mutation, {
778
+ transcriptId: params.transcript_id,
779
+ startTime: params.start_time,
780
+ endTime: params.end_time,
781
+ name: params.name,
782
+ mediaType: params.media_type,
783
+ summary: params.summary,
784
+ privacies: params.privacies
785
+ });
786
+ return data.createBite;
787
+ }
788
+ };
789
+ }
790
+
791
+ // src/graphql/queries/meetings.ts
792
+ var ACTIVE_MEETING_FIELDS = `
793
+ id
794
+ title
795
+ organizer_email
796
+ meeting_link
797
+ start_time
798
+ end_time
799
+ privacy
800
+ state
801
+ `;
802
+ function createMeetingsAPI(client) {
803
+ return {
804
+ async active(params) {
805
+ const query = `
806
+ query ActiveMeetings($email: String, $states: [MeetingState!]) {
807
+ active_meetings(input: { email: $email, states: $states }) {
808
+ ${ACTIVE_MEETING_FIELDS}
809
+ }
810
+ }
811
+ `;
812
+ const data = await client.execute(query, {
813
+ email: params?.email,
814
+ states: params?.states
815
+ });
816
+ return data.active_meetings;
817
+ },
818
+ async addBot(params) {
819
+ const mutation = `
820
+ mutation AddToLiveMeeting(
821
+ $meetingLink: String!
822
+ $title: String
823
+ $meetingPassword: String
824
+ $duration: Int
825
+ $language: String
826
+ ) {
827
+ addToLiveMeeting(
828
+ meeting_link: $meetingLink
829
+ title: $title
830
+ meeting_password: $meetingPassword
831
+ duration: $duration
832
+ language: $language
833
+ ) {
834
+ success
835
+ }
836
+ }
837
+ `;
838
+ const data = await client.execute(mutation, {
839
+ meetingLink: params.meeting_link,
840
+ title: params.title,
841
+ meetingPassword: params.password,
842
+ duration: params.duration,
843
+ language: params.language
844
+ });
845
+ return data.addToLiveMeeting;
846
+ }
847
+ };
848
+ }
849
+
850
+ // src/helpers/action-items.ts
851
+ var ASSIGNEE_PATTERNS = [
852
+ { pattern: /@(\w+)/i, group: 1 },
853
+ // @Alice
854
+ { pattern: /^(\w+):/i, group: 1 },
855
+ // Alice: at start
856
+ { pattern: /assigned to (\w+)/i, group: 1 },
857
+ // assigned to Alice
858
+ { pattern: /(\w+) will\b/i, group: 1 },
859
+ // Alice will
860
+ { pattern: /(\w+) to\b/i, group: 1 },
861
+ // Alice to (do something)
862
+ { pattern: /\s-\s*(\w+)$/i, group: 1 }
863
+ // ... - Alice
864
+ ];
865
+ var DUE_DATE_PATTERNS = [
866
+ { pattern: /by (monday|tuesday|wednesday|thursday|friday|saturday|sunday)/i, group: 1 },
867
+ { pattern: /by (tomorrow|today)/i, group: 1 },
868
+ { pattern: /by (EOD|end of day)/i, group: 1 },
869
+ { pattern: /by (EOW|end of week)/i, group: 1 },
870
+ { pattern: /due (\d{4}-\d{2}-\d{2})/i, group: 1 },
871
+ { pattern: /due (jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\s+\d+/i, group: 0 },
872
+ { pattern: /by (\d{1,2}\/\d{1,2})/i, group: 1 }
873
+ ];
874
+ var LIST_PREFIX_PATTERN = /^(?:[-•*]|\d+\.)\s*/;
875
+ var SECTION_HEADER_PATTERN = /^\*\*(.+)\*\*$/;
876
+ function extractActionItems(transcript, options = {}) {
877
+ const actionItemsText = transcript.summary?.action_items;
878
+ if (!actionItemsText || actionItemsText.trim().length === 0) {
879
+ return emptyResult();
880
+ }
881
+ const config = {
882
+ detectAssignees: options.detectAssignees ?? true,
883
+ detectDueDates: options.detectDueDates ?? true,
884
+ includeSourceSentences: options.includeSourceSentences ?? false,
885
+ participantNames: options.participantNames ?? []
886
+ };
887
+ const taskSentences = config.includeSourceSentences ? buildTaskSentenceLookup(transcript) : [];
888
+ const lines = actionItemsText.split(/\n/);
889
+ return parseAllLines(lines, config, taskSentences);
890
+ }
891
+ function parseAllLines(lines, config, taskSentences) {
892
+ const items = [];
893
+ const assigneeSet = /* @__PURE__ */ new Set();
894
+ let currentSectionAssignee;
895
+ for (let i = 0; i < lines.length; i++) {
896
+ const result = processLine(lines[i], i + 1, config, taskSentences, currentSectionAssignee);
897
+ if (result.type === "header") {
898
+ currentSectionAssignee = result.assignee;
899
+ } else if (result.type === "item" && result.item) {
900
+ items.push(result.item);
901
+ if (result.item.assignee) {
902
+ assigneeSet.add(result.item.assignee);
903
+ }
904
+ }
905
+ }
906
+ return buildResult(items, assigneeSet);
907
+ }
908
+ function processLine(line, lineNumber, config, taskSentences, sectionAssignee) {
909
+ if (!line) return { type: "skip" };
910
+ const trimmed = line.trim();
911
+ if (trimmed.length === 0) return { type: "skip" };
912
+ const headerMatch = trimmed.match(SECTION_HEADER_PATTERN);
913
+ if (headerMatch?.[1]) {
914
+ const headerName = headerMatch[1];
915
+ const assignee = headerName.toLowerCase() === "unassigned" ? void 0 : headerName;
916
+ return { type: "header", assignee };
917
+ }
918
+ const item = parseLine(line, lineNumber, config, taskSentences, sectionAssignee);
919
+ if (item) {
920
+ return { type: "item", item };
921
+ }
922
+ return { type: "skip" };
923
+ }
924
+ function parseLine(line, lineNumber, config, taskSentences, sectionAssignee) {
925
+ if (!line) return null;
926
+ const trimmed = line.trim();
927
+ if (trimmed.length === 0) return null;
928
+ const text = trimmed.replace(LIST_PREFIX_PATTERN, "");
929
+ if (text.length === 0) return null;
930
+ const inlineAssignee = config.detectAssignees ? detectAssignee(text, config.participantNames) : void 0;
931
+ const assignee = inlineAssignee ?? sectionAssignee;
932
+ const dueDate = config.detectDueDates ? detectDueDate(text) : void 0;
933
+ const sourceSentence = config.includeSourceSentences ? findSourceSentence(text, taskSentences) : void 0;
934
+ return { text, assignee, dueDate, lineNumber, sourceSentence };
935
+ }
936
+ function buildResult(items, assigneeSet) {
937
+ return {
938
+ items,
939
+ totalItems: items.length,
940
+ assignedItems: items.filter((i) => i.assignee !== void 0).length,
941
+ datedItems: items.filter((i) => i.dueDate !== void 0).length,
942
+ assignees: Array.from(assigneeSet)
943
+ };
944
+ }
945
+ function emptyResult() {
946
+ return {
947
+ items: [],
948
+ totalItems: 0,
949
+ assignedItems: 0,
950
+ datedItems: 0,
951
+ assignees: []
952
+ };
953
+ }
954
+ function detectAssignee(text, participantNames) {
955
+ const participantSet = new Set(participantNames.map((n) => n.toLowerCase()));
956
+ const filterByParticipants = participantSet.size > 0;
957
+ for (const { pattern, group } of ASSIGNEE_PATTERNS) {
958
+ const match = text.match(pattern);
959
+ if (match?.[group]) {
960
+ const name = match[group];
961
+ if (filterByParticipants) {
962
+ if (participantSet.has(name.toLowerCase())) {
963
+ return name;
964
+ }
965
+ continue;
966
+ }
967
+ return name;
968
+ }
969
+ }
970
+ return void 0;
971
+ }
972
+ function detectDueDate(text) {
973
+ for (const { pattern, group } of DUE_DATE_PATTERNS) {
974
+ const match = text.match(pattern);
975
+ if (match) {
976
+ if (group === 0 && match[0]) {
977
+ const fullMatch = match[0];
978
+ const dateMatch = fullMatch.match(
979
+ /(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\s+\d+/i
980
+ );
981
+ if (dateMatch?.[0]) {
982
+ return dateMatch[0];
983
+ }
984
+ }
985
+ if (match[group]) {
986
+ return match[group];
987
+ }
988
+ }
989
+ }
990
+ return void 0;
991
+ }
992
+ function buildTaskSentenceLookup(transcript) {
993
+ const sentences = transcript.sentences ?? [];
994
+ const result = [];
995
+ for (const sentence of sentences) {
996
+ const task = sentence.ai_filters?.task;
997
+ if (task) {
998
+ result.push({
999
+ text: sentence.text,
1000
+ task: task.toLowerCase(),
1001
+ speakerName: sentence.speaker_name,
1002
+ startTime: Number.parseFloat(sentence.start_time)
1003
+ });
1004
+ }
1005
+ }
1006
+ return result;
1007
+ }
1008
+ function findSourceSentence(actionItemText, taskSentences) {
1009
+ const normalizedItem = actionItemText.toLowerCase();
1010
+ for (const sentence of taskSentences) {
1011
+ if (normalizedItem.includes(sentence.task) || sentence.task.includes(normalizedItem)) {
1012
+ return {
1013
+ speakerName: sentence.speakerName,
1014
+ text: sentence.text,
1015
+ startTime: sentence.startTime
1016
+ };
1017
+ }
1018
+ const itemWords = new Set(normalizedItem.split(/\s+/).filter((w) => w.length > 3));
1019
+ const taskWords = sentence.task.split(/\s+/).filter((w) => w.length > 3);
1020
+ const matchingWords = taskWords.filter((w) => itemWords.has(w));
1021
+ if (taskWords.length > 0 && matchingWords.length / taskWords.length >= 0.5) {
1022
+ return {
1023
+ speakerName: sentence.speakerName,
1024
+ text: sentence.text,
1025
+ startTime: sentence.startTime
1026
+ };
1027
+ }
1028
+ }
1029
+ return void 0;
1030
+ }
1031
+
1032
+ // src/helpers/action-items-format.ts
1033
+ function filterActionItems(items, options) {
1034
+ const { assignees, assignedOnly, datedOnly } = options;
1035
+ const normalizedAssignees = assignees?.map((a) => a.toLowerCase());
1036
+ return items.filter((item) => {
1037
+ if (normalizedAssignees && normalizedAssignees.length > 0) {
1038
+ if (!item.assignee) return false;
1039
+ if (!normalizedAssignees.includes(item.assignee.toLowerCase())) return false;
1040
+ }
1041
+ if (assignedOnly && !item.assignee) {
1042
+ return false;
1043
+ }
1044
+ if (datedOnly && !item.dueDate) {
1045
+ return false;
1046
+ }
1047
+ return true;
1048
+ });
1049
+ }
1050
+ function aggregateActionItems(transcripts, extractionOptions, filterOptions) {
1051
+ if (transcripts.length === 0) {
1052
+ return emptyAggregatedResult();
1053
+ }
1054
+ const allItems = [];
1055
+ let transcriptsWithItems = 0;
1056
+ for (const transcript of transcripts) {
1057
+ const extracted = extractActionItems(transcript, extractionOptions);
1058
+ if (extracted.items.length > 0) {
1059
+ transcriptsWithItems++;
1060
+ for (const item of extracted.items) {
1061
+ allItems.push({
1062
+ ...item,
1063
+ transcriptId: transcript.id,
1064
+ transcriptTitle: transcript.title,
1065
+ transcriptDate: transcript.dateString
1066
+ });
1067
+ }
1068
+ }
1069
+ }
1070
+ const filteredItems = filterOptions ? filterActionItems(allItems, filterOptions) : allItems;
1071
+ return buildAggregatedResult(filteredItems, transcripts.length, transcriptsWithItems);
1072
+ }
1073
+ function emptyAggregatedResult() {
1074
+ return {
1075
+ items: [],
1076
+ totalItems: 0,
1077
+ transcriptsProcessed: 0,
1078
+ transcriptsWithItems: 0,
1079
+ assignedItems: 0,
1080
+ datedItems: 0,
1081
+ assignees: [],
1082
+ dateRange: { earliest: "", latest: "" }
1083
+ };
1084
+ }
1085
+ function buildAggregatedResult(items, transcriptsProcessed, transcriptsWithItems) {
1086
+ const assigneeSet = /* @__PURE__ */ new Set();
1087
+ let assignedItems = 0;
1088
+ let datedItems = 0;
1089
+ for (const item of items) {
1090
+ if (item.assignee) {
1091
+ assigneeSet.add(item.assignee);
1092
+ assignedItems++;
1093
+ }
1094
+ if (item.dueDate) {
1095
+ datedItems++;
1096
+ }
1097
+ }
1098
+ const dates = items.map((i) => i.transcriptDate).filter(Boolean).sort();
1099
+ return {
1100
+ items,
1101
+ totalItems: items.length,
1102
+ transcriptsProcessed,
1103
+ transcriptsWithItems,
1104
+ assignedItems,
1105
+ datedItems,
1106
+ assignees: Array.from(assigneeSet),
1107
+ dateRange: {
1108
+ earliest: dates[0] ?? "",
1109
+ latest: dates[dates.length - 1] ?? ""
1110
+ }
1111
+ };
1112
+ }
1113
+ function isAggregatedResult(result) {
1114
+ return "transcriptsProcessed" in result;
1115
+ }
1116
+ function isAggregatedItem(item) {
1117
+ return "transcriptId" in item;
1118
+ }
1119
+ function escapeMarkdown(text) {
1120
+ return text.replace(/\\/g, "\\\\").replace(/\*/g, "\\*").replace(/#/g, "\\#").replace(/\[/g, "\\[").replace(/\]/g, "\\]").replace(/_/g, "\\_").replace(/`/g, "\\`");
1121
+ }
1122
+ function getPresetOptions(preset) {
1123
+ switch (preset) {
1124
+ case "notion":
1125
+ return {
1126
+ style: "checkbox",
1127
+ includeAssignee: true,
1128
+ includeDueDate: true
1129
+ };
1130
+ case "obsidian":
1131
+ return {
1132
+ style: "checkbox",
1133
+ includeAssignee: false,
1134
+ includeDueDate: true
1135
+ };
1136
+ case "github":
1137
+ return {
1138
+ style: "checkbox",
1139
+ includeAssignee: true,
1140
+ includeDueDate: true
1141
+ };
1142
+ default:
1143
+ return {};
1144
+ }
1145
+ }
1146
+ function formatItem(item, index, options) {
1147
+ const { style, includeAssignee, includeDueDate, includeMeetingTitle } = options;
1148
+ let prefix;
1149
+ switch (style) {
1150
+ case "bullet":
1151
+ prefix = "-";
1152
+ break;
1153
+ case "numbered":
1154
+ prefix = `${index + 1}.`;
1155
+ break;
1156
+ default:
1157
+ prefix = "- [ ]";
1158
+ break;
1159
+ }
1160
+ let text = escapeMarkdown(item.text);
1161
+ const metadata = [];
1162
+ if (includeAssignee && item.assignee) {
1163
+ metadata.push(`@${item.assignee}`);
1164
+ }
1165
+ if (includeDueDate && item.dueDate) {
1166
+ metadata.push(`due: ${item.dueDate}`);
1167
+ }
1168
+ if (includeMeetingTitle && isAggregatedItem(item)) {
1169
+ metadata.push(`*${item.transcriptTitle}*`);
1170
+ }
1171
+ if (metadata.length > 0) {
1172
+ text += ` (${metadata.join(", ")})`;
1173
+ }
1174
+ return `${prefix} ${text}`;
1175
+ }
1176
+ function groupBy(items, keyFn) {
1177
+ const groups = /* @__PURE__ */ new Map();
1178
+ for (const item of items) {
1179
+ const key = keyFn(item);
1180
+ const group = groups.get(key);
1181
+ if (group) {
1182
+ group.push(item);
1183
+ } else {
1184
+ groups.set(key, [item]);
1185
+ }
1186
+ }
1187
+ return groups;
1188
+ }
1189
+ function formatSummaryLine(result) {
1190
+ return `**Summary:** ${result.totalItems} items from ${result.transcriptsProcessed} meetings (${result.assignedItems} assigned, ${result.datedItems} with due dates)`;
1191
+ }
1192
+ function sortGroupKeys(keys) {
1193
+ return keys.sort((a, b) => {
1194
+ if (a === "Unassigned") return 1;
1195
+ if (b === "Unassigned") return -1;
1196
+ return a.localeCompare(b);
1197
+ });
1198
+ }
1199
+ function formatGroupedItems(result, groupByOption, itemOptions) {
1200
+ const lines = [];
1201
+ const keyFn = getGroupKeyFn(groupByOption);
1202
+ const groups = groupBy(result.items, keyFn);
1203
+ const sortedKeys = sortGroupKeys(Array.from(groups.keys()));
1204
+ for (const key of sortedKeys) {
1205
+ const groupItems = groups.get(key);
1206
+ if (!groupItems) continue;
1207
+ lines.push(`### ${key}`);
1208
+ lines.push("");
1209
+ groupItems.forEach((item, index) => {
1210
+ lines.push(formatItem(item, index, itemOptions));
1211
+ });
1212
+ lines.push("");
1213
+ }
1214
+ return lines;
1215
+ }
1216
+ function formatFlatItems(items, itemOptions) {
1217
+ return items.map((item, index) => formatItem(item, index, itemOptions));
1218
+ }
1219
+ function formatActionItemsMarkdown(result, options = {}) {
1220
+ if (result.items.length === 0) {
1221
+ return "";
1222
+ }
1223
+ const presetOptions = getPresetOptions(options.preset);
1224
+ const mergedOptions = { ...presetOptions, ...options };
1225
+ const {
1226
+ style = "checkbox",
1227
+ groupBy: groupByOption = "none",
1228
+ includeAssignee = false,
1229
+ includeDueDate = false,
1230
+ includeMeetingTitle = false,
1231
+ includeSummary = false
1232
+ } = mergedOptions;
1233
+ const lines = [];
1234
+ if (includeSummary && isAggregatedResult(result)) {
1235
+ lines.push(formatSummaryLine(result));
1236
+ lines.push("");
1237
+ }
1238
+ const itemOptions = { style, includeAssignee, includeDueDate, includeMeetingTitle };
1239
+ const shouldGroup = groupByOption !== "none" && isAggregatedResult(result);
1240
+ if (shouldGroup) {
1241
+ lines.push(...formatGroupedItems(result, groupByOption, itemOptions));
1242
+ } else {
1243
+ lines.push(...formatFlatItems(result.items, itemOptions));
1244
+ }
1245
+ return lines.join("\n").trim();
1246
+ }
1247
+ function getGroupKeyFn(groupBy2) {
1248
+ switch (groupBy2) {
1249
+ case "assignee":
1250
+ return (item) => item.assignee ?? "Unassigned";
1251
+ case "transcript":
1252
+ return (item) => item.transcriptTitle;
1253
+ case "date":
1254
+ return (item) => item.transcriptDate;
1255
+ }
1256
+ }
1257
+
1258
+ // src/helpers/domain-utils.ts
1259
+ function extractDomain(email) {
1260
+ const atIndex = email.indexOf("@");
1261
+ if (atIndex < 0) return "";
1262
+ const domain = email.slice(atIndex + 1).toLowerCase();
1263
+ return domain || "";
1264
+ }
1265
+ function hasExternalParticipants(participants, internalDomain) {
1266
+ const normalizedInternal = internalDomain.toLowerCase();
1267
+ return participants.some((email) => {
1268
+ const domain = extractDomain(email);
1269
+ return domain !== "" && domain !== normalizedInternal;
1270
+ });
1271
+ }
1272
+
1273
+ // src/helpers/meeting-insights.ts
1274
+ function analyzeMeetings(transcripts, options = {}) {
1275
+ const { speakers, groupBy: groupBy2, topSpeakersCount = 10, topParticipantsCount = 10 } = options;
1276
+ if (transcripts.length === 0) {
1277
+ return emptyInsights();
1278
+ }
1279
+ const totalDurationMinutes = sumDurations(transcripts);
1280
+ const averageDurationMinutes = totalDurationMinutes / transcripts.length;
1281
+ const byDayOfWeek = calculateDayOfWeekStats(transcripts);
1282
+ const byTimeGroup = groupBy2 ? calculateTimeGroupStats(transcripts, groupBy2) : void 0;
1283
+ const participantData = aggregateParticipants(transcripts);
1284
+ const totalUniqueParticipants = participantData.uniqueEmails.size;
1285
+ const averageParticipantsPerMeeting = calculateAverageParticipants(transcripts);
1286
+ const topParticipants = buildTopParticipants(participantData.stats, topParticipantsCount);
1287
+ const speakerData = aggregateSpeakers(transcripts, speakers);
1288
+ const totalUniqueSpeakers = speakerData.uniqueNames.size;
1289
+ const topSpeakers = buildTopSpeakers(speakerData.stats, topSpeakersCount);
1290
+ const { earliestMeeting, latestMeeting } = findDateRange(transcripts);
1291
+ return {
1292
+ totalMeetings: transcripts.length,
1293
+ totalDurationMinutes,
1294
+ averageDurationMinutes,
1295
+ byDayOfWeek,
1296
+ byTimeGroup,
1297
+ totalUniqueParticipants,
1298
+ averageParticipantsPerMeeting,
1299
+ topParticipants,
1300
+ totalUniqueSpeakers,
1301
+ topSpeakers,
1302
+ earliestMeeting,
1303
+ latestMeeting
1304
+ };
1305
+ }
1306
+ function emptyInsights() {
1307
+ return {
1308
+ totalMeetings: 0,
1309
+ totalDurationMinutes: 0,
1310
+ averageDurationMinutes: 0,
1311
+ byDayOfWeek: emptyDayOfWeekStats(),
1312
+ byTimeGroup: void 0,
1313
+ totalUniqueParticipants: 0,
1314
+ averageParticipantsPerMeeting: 0,
1315
+ topParticipants: [],
1316
+ totalUniqueSpeakers: 0,
1317
+ topSpeakers: [],
1318
+ earliestMeeting: "",
1319
+ latestMeeting: ""
1320
+ };
1321
+ }
1322
+ function emptyDayOfWeekStats() {
1323
+ const emptyDay = () => ({ count: 0, totalMinutes: 0 });
1324
+ return {
1325
+ monday: emptyDay(),
1326
+ tuesday: emptyDay(),
1327
+ wednesday: emptyDay(),
1328
+ thursday: emptyDay(),
1329
+ friday: emptyDay(),
1330
+ saturday: emptyDay(),
1331
+ sunday: emptyDay()
1332
+ };
1333
+ }
1334
+ function sumDurations(transcripts) {
1335
+ return transcripts.reduce((sum, t) => sum + (t.duration ?? 0), 0);
1336
+ }
1337
+ function calculateDayOfWeekStats(transcripts) {
1338
+ const stats = emptyDayOfWeekStats();
1339
+ const dayNames = [
1340
+ "sunday",
1341
+ "monday",
1342
+ "tuesday",
1343
+ "wednesday",
1344
+ "thursday",
1345
+ "friday",
1346
+ "saturday"
1347
+ ];
1348
+ for (const t of transcripts) {
1349
+ const date = parseDate(t.dateString);
1350
+ if (!date) continue;
1351
+ const dayIndex = date.getUTCDay();
1352
+ const dayName = dayNames[dayIndex];
1353
+ if (dayName) {
1354
+ stats[dayName].count++;
1355
+ stats[dayName].totalMinutes += t.duration ?? 0;
1356
+ }
1357
+ }
1358
+ return stats;
1359
+ }
1360
+ function calculateTimeGroupStats(transcripts, groupBy2) {
1361
+ const groups = /* @__PURE__ */ new Map();
1362
+ for (const t of transcripts) {
1363
+ const date = parseDate(t.dateString);
1364
+ if (!date) continue;
1365
+ const period = formatPeriod(date, groupBy2);
1366
+ const existing = groups.get(period) ?? { count: 0, totalMinutes: 0 };
1367
+ existing.count++;
1368
+ existing.totalMinutes += t.duration ?? 0;
1369
+ groups.set(period, existing);
1370
+ }
1371
+ const result = [];
1372
+ for (const [period, data] of groups) {
1373
+ result.push({
1374
+ period,
1375
+ count: data.count,
1376
+ totalMinutes: data.totalMinutes,
1377
+ averageMinutes: data.totalMinutes / data.count
1378
+ });
1379
+ }
1380
+ result.sort((a, b) => a.period.localeCompare(b.period));
1381
+ return result;
1382
+ }
1383
+ function formatPeriod(date, groupBy2) {
1384
+ const year = date.getUTCFullYear();
1385
+ const month = String(date.getUTCMonth() + 1).padStart(2, "0");
1386
+ const day = String(date.getUTCDate()).padStart(2, "0");
1387
+ switch (groupBy2) {
1388
+ case "day":
1389
+ return `${year}-${month}-${day}`;
1390
+ case "week":
1391
+ return getISOWeek(date);
1392
+ case "month":
1393
+ return `${year}-${month}`;
1394
+ }
1395
+ }
1396
+ function getISOWeek(date) {
1397
+ const d = new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate()));
1398
+ d.setUTCDate(d.getUTCDate() + 4 - (d.getUTCDay() || 7));
1399
+ const yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1));
1400
+ const weekNumber = Math.ceil(((d.getTime() - yearStart.getTime()) / 864e5 + 1) / 7);
1401
+ return `${d.getUTCFullYear()}-W${String(weekNumber).padStart(2, "0")}`;
1402
+ }
1403
+ function aggregateParticipants(transcripts) {
1404
+ const uniqueEmails = /* @__PURE__ */ new Set();
1405
+ const stats = /* @__PURE__ */ new Map();
1406
+ for (const t of transcripts) {
1407
+ const participants = t.participants ?? [];
1408
+ const seenInMeeting = /* @__PURE__ */ new Set();
1409
+ for (const email of participants) {
1410
+ const normalizedEmail = email.toLowerCase();
1411
+ uniqueEmails.add(normalizedEmail);
1412
+ if (seenInMeeting.has(normalizedEmail)) continue;
1413
+ seenInMeeting.add(normalizedEmail);
1414
+ const existing = stats.get(normalizedEmail) ?? { meetingCount: 0, totalMinutes: 0 };
1415
+ existing.meetingCount++;
1416
+ existing.totalMinutes += t.duration ?? 0;
1417
+ stats.set(normalizedEmail, existing);
1418
+ }
1419
+ }
1420
+ return { uniqueEmails, stats };
1421
+ }
1422
+ function calculateAverageParticipants(transcripts) {
1423
+ if (transcripts.length === 0) return 0;
1424
+ let totalParticipants = 0;
1425
+ for (const t of transcripts) {
1426
+ const unique = new Set((t.participants ?? []).map((p) => p.toLowerCase()));
1427
+ totalParticipants += unique.size;
1428
+ }
1429
+ return totalParticipants / transcripts.length;
1430
+ }
1431
+ function buildTopParticipants(stats, limit) {
1432
+ const result = [];
1433
+ for (const [email, data] of stats) {
1434
+ result.push({
1435
+ email,
1436
+ meetingCount: data.meetingCount,
1437
+ totalMinutes: data.totalMinutes
1438
+ });
1439
+ }
1440
+ result.sort((a, b) => b.meetingCount - a.meetingCount);
1441
+ return result.slice(0, limit);
1442
+ }
1443
+ function aggregateSpeakers(transcripts, filterSpeakers) {
1444
+ const uniqueNames = /* @__PURE__ */ new Set();
1445
+ const stats = /* @__PURE__ */ new Map();
1446
+ const filterSet = filterSpeakers ? new Set(filterSpeakers) : null;
1447
+ for (const t of transcripts) {
1448
+ const sentences = t.sentences ?? [];
1449
+ for (const sentence of sentences) {
1450
+ const speakerName = sentence.speaker_name;
1451
+ if (filterSet && !filterSet.has(speakerName)) continue;
1452
+ uniqueNames.add(speakerName);
1453
+ const existing = stats.get(speakerName) ?? {
1454
+ meetingCount: 0,
1455
+ totalTalkTimeSeconds: 0,
1456
+ meetings: /* @__PURE__ */ new Set()
1457
+ };
1458
+ const duration = parseSentenceDuration(sentence);
1459
+ existing.totalTalkTimeSeconds += duration;
1460
+ if (!existing.meetings.has(t.id)) {
1461
+ existing.meetings.add(t.id);
1462
+ existing.meetingCount++;
1463
+ }
1464
+ stats.set(speakerName, existing);
1465
+ }
1466
+ }
1467
+ return { uniqueNames, stats };
1468
+ }
1469
+ function parseSentenceDuration(sentence) {
1470
+ const start = Number.parseFloat(sentence.start_time);
1471
+ const end = Number.parseFloat(sentence.end_time);
1472
+ return Math.max(0, end - start);
1473
+ }
1474
+ function buildTopSpeakers(stats, limit) {
1475
+ const result = [];
1476
+ for (const [name, data] of stats) {
1477
+ result.push({
1478
+ name,
1479
+ meetingCount: data.meetingCount,
1480
+ totalTalkTimeSeconds: data.totalTalkTimeSeconds,
1481
+ averageTalkTimeSeconds: data.meetingCount > 0 ? data.totalTalkTimeSeconds / data.meetingCount : 0
1482
+ });
1483
+ }
1484
+ result.sort((a, b) => b.totalTalkTimeSeconds - a.totalTalkTimeSeconds);
1485
+ return result.slice(0, limit);
1486
+ }
1487
+ function findDateRange(transcripts) {
1488
+ let earliest = null;
1489
+ let latest = null;
1490
+ for (const t of transcripts) {
1491
+ const date = parseDate(t.dateString);
1492
+ if (!date) continue;
1493
+ if (!earliest || date < earliest) {
1494
+ earliest = date;
1495
+ }
1496
+ if (!latest || date > latest) {
1497
+ latest = date;
1498
+ }
1499
+ }
1500
+ return {
1501
+ earliestMeeting: earliest ? formatDateOnly(earliest) : "",
1502
+ latestMeeting: latest ? formatDateOnly(latest) : ""
1503
+ };
1504
+ }
1505
+ function parseDate(dateString) {
1506
+ if (!dateString) return null;
1507
+ const date = new Date(dateString);
1508
+ return Number.isNaN(date.getTime()) ? null : date;
1509
+ }
1510
+ function formatDateOnly(date) {
1511
+ const year = date.getUTCFullYear();
1512
+ const month = String(date.getUTCMonth() + 1).padStart(2, "0");
1513
+ const day = String(date.getUTCDate()).padStart(2, "0");
1514
+ return `${year}-${month}-${day}`;
1515
+ }
1516
+
1517
+ // src/helpers/search.ts
1518
+ function escapeRegex(str) {
1519
+ return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1520
+ }
1521
+ function matchesSpeaker(sentence, speakerSet) {
1522
+ if (!speakerSet) return true;
1523
+ return speakerSet.has(sentence.speaker_name.toLowerCase());
1524
+ }
1525
+ function matchesAIFilters(sentence, filterQuestions, filterTasks) {
1526
+ if (!filterQuestions && !filterTasks) return true;
1527
+ const hasQuestion = Boolean(sentence.ai_filters?.question);
1528
+ const hasTask = Boolean(sentence.ai_filters?.task);
1529
+ if (filterQuestions && filterTasks) {
1530
+ return hasQuestion || hasTask;
1531
+ }
1532
+ if (filterQuestions) return hasQuestion;
1533
+ if (filterTasks) return hasTask;
1534
+ return true;
1535
+ }
1536
+ function extractContext(sentences, index, contextLines) {
1537
+ const beforeStart = Math.max(0, index - contextLines);
1538
+ const afterEnd = Math.min(sentences.length, index + contextLines + 1);
1539
+ return {
1540
+ before: sentences.slice(beforeStart, index).map((s) => ({
1541
+ speakerName: s.speaker_name,
1542
+ text: s.text
1543
+ })),
1544
+ after: sentences.slice(index + 1, afterEnd).map((s) => ({
1545
+ speakerName: s.speaker_name,
1546
+ text: s.text
1547
+ }))
1548
+ };
1549
+ }
1550
+ function sentenceToMatch(sentence, transcript, context) {
1551
+ return {
1552
+ transcriptId: transcript.id,
1553
+ transcriptTitle: transcript.title,
1554
+ transcriptDate: transcript.dateString,
1555
+ transcriptUrl: transcript.transcript_url,
1556
+ sentence: {
1557
+ index: sentence.index,
1558
+ text: sentence.text,
1559
+ speakerName: sentence.speaker_name,
1560
+ startTime: Number.parseFloat(sentence.start_time),
1561
+ endTime: Number.parseFloat(sentence.end_time),
1562
+ isQuestion: Boolean(sentence.ai_filters?.question),
1563
+ isTask: Boolean(sentence.ai_filters?.task)
1564
+ },
1565
+ context
1566
+ };
1567
+ }
1568
+ function searchTranscript(transcript, options) {
1569
+ const {
1570
+ query,
1571
+ caseSensitive = false,
1572
+ speakers,
1573
+ filterQuestions = false,
1574
+ filterTasks = false,
1575
+ contextLines = 1
1576
+ } = options;
1577
+ if (!query || query.trim() === "") {
1578
+ return [];
1579
+ }
1580
+ const sentences = transcript.sentences ?? [];
1581
+ if (sentences.length === 0) {
1582
+ return [];
1583
+ }
1584
+ const escapedQuery = escapeRegex(query);
1585
+ const regex = new RegExp(escapedQuery, caseSensitive ? "" : "i");
1586
+ const speakerSet = speakers ? new Set(speakers.map((s) => s.toLowerCase())) : null;
1587
+ const matches = [];
1588
+ for (let i = 0; i < sentences.length; i++) {
1589
+ const sentence = sentences[i];
1590
+ if (!sentence) continue;
1591
+ if (!regex.test(sentence.text)) continue;
1592
+ if (!matchesSpeaker(sentence, speakerSet)) continue;
1593
+ if (!matchesAIFilters(sentence, filterQuestions, filterTasks)) continue;
1594
+ const context = extractContext(sentences, i, contextLines);
1595
+ matches.push(sentenceToMatch(sentence, transcript, context));
1596
+ }
1597
+ return matches;
1598
+ }
1599
+
1600
+ // src/graphql/queries/transcripts.ts
1601
+ var TRANSCRIPT_BASE_FIELDS = `
1602
+ id
1603
+ title
1604
+ organizer_email
1605
+ host_email
1606
+ user {
1607
+ user_id
1608
+ email
1609
+ name
1610
+ }
1611
+ speakers {
1612
+ id
1613
+ name
1614
+ }
1615
+ transcript_url
1616
+ participants
1617
+ meeting_attendees {
1618
+ displayName
1619
+ email
1620
+ phoneNumber
1621
+ name
1622
+ location
1623
+ }
1624
+ meeting_attendance {
1625
+ name
1626
+ join_time
1627
+ leave_time
1628
+ }
1629
+ fireflies_users
1630
+ workspace_users
1631
+ duration
1632
+ dateString
1633
+ date
1634
+ audio_url
1635
+ video_url
1636
+ calendar_id
1637
+ meeting_info {
1638
+ fred_joined
1639
+ silent_meeting
1640
+ summary_status
1641
+ }
1642
+ cal_id
1643
+ calendar_type
1644
+ apps_preview {
1645
+ outputs {
1646
+ transcript_id
1647
+ user_id
1648
+ app_id
1649
+ created_at
1650
+ title
1651
+ prompt
1652
+ response
1653
+ }
1654
+ }
1655
+ meeting_link
1656
+ analytics {
1657
+ sentiments {
1658
+ negative_pct
1659
+ neutral_pct
1660
+ positive_pct
1661
+ }
1662
+ }
1663
+ channels {
1664
+ id
1665
+ title
1666
+ is_private
1667
+ created_at
1668
+ updated_at
1669
+ created_by
1670
+ members {
1671
+ user_id
1672
+ email
1673
+ name
1674
+ }
1675
+ }
1676
+ `;
1677
+ var SENTENCES_FIELDS = `
1678
+ sentences {
1679
+ index
1680
+ text
1681
+ raw_text
1682
+ start_time
1683
+ end_time
1684
+ speaker_id
1685
+ speaker_name
1686
+ ai_filters {
1687
+ task
1688
+ pricing
1689
+ metric
1690
+ question
1691
+ date_and_time
1692
+ text_cleanup
1693
+ sentiment
1694
+ }
1695
+ }
1696
+ `;
1697
+ var SUMMARY_FIELDS = `
1698
+ summary {
1699
+ action_items
1700
+ keywords
1701
+ outline
1702
+ overview
1703
+ shorthand_bullet
1704
+ notes
1705
+ gist
1706
+ bullet_gist
1707
+ short_summary
1708
+ short_overview
1709
+ meeting_type
1710
+ topics_discussed
1711
+ transcript_chapters
1712
+ extended_sections {
1713
+ title
1714
+ content
1715
+ }
1716
+ }
1717
+ `;
1718
+ function buildTranscriptFields(params) {
1719
+ const includeSentences = params?.includeSentences !== false;
1720
+ const includeSummary = params?.includeSummary !== false;
1721
+ let fields = TRANSCRIPT_BASE_FIELDS;
1722
+ if (includeSentences) {
1723
+ fields += SENTENCES_FIELDS;
1724
+ }
1725
+ if (includeSummary) {
1726
+ fields += SUMMARY_FIELDS;
1727
+ }
1728
+ return fields;
1729
+ }
1730
+ var TRANSCRIPT_LIST_FIELDS = `
1731
+ id
1732
+ title
1733
+ organizer_email
1734
+ transcript_url
1735
+ participants
1736
+ duration
1737
+ dateString
1738
+ date
1739
+ video_url
1740
+ meeting_info {
1741
+ fred_joined
1742
+ silent_meeting
1743
+ summary_status
1744
+ }
1745
+ `;
1746
+ function createTranscriptsAPI(client) {
1747
+ return {
1748
+ async get(id, params) {
1749
+ const fields = buildTranscriptFields(params);
1750
+ const query = `
1751
+ query GetTranscript($id: String!) {
1752
+ transcript(id: $id) {
1753
+ ${fields}
1754
+ }
1755
+ }
1756
+ `;
1757
+ const data = await client.execute(query, { id });
1758
+ return normalizeTranscript(data.transcript);
1759
+ },
1760
+ async list(params) {
1761
+ const query = `
1762
+ query ListTranscripts(
1763
+ $keyword: String
1764
+ $scope: String
1765
+ $organizers: [String!]
1766
+ $participants: [String!]
1767
+ $user_id: String
1768
+ $mine: Boolean
1769
+ $channel_id: String
1770
+ $fromDate: DateTime
1771
+ $toDate: DateTime
1772
+ $limit: Int
1773
+ $skip: Int
1774
+ $title: String
1775
+ $host_email: String
1776
+ $organizer_email: String
1777
+ $participant_email: String
1778
+ $date: Float
1779
+ ) {
1780
+ transcripts(
1781
+ keyword: $keyword
1782
+ scope: $scope
1783
+ organizers: $organizers
1784
+ participants: $participants
1785
+ user_id: $user_id
1786
+ mine: $mine
1787
+ channel_id: $channel_id
1788
+ fromDate: $fromDate
1789
+ toDate: $toDate
1790
+ limit: $limit
1791
+ skip: $skip
1792
+ title: $title
1793
+ host_email: $host_email
1794
+ organizer_email: $organizer_email
1795
+ participant_email: $participant_email
1796
+ date: $date
1797
+ ) {
1798
+ ${TRANSCRIPT_LIST_FIELDS}
1799
+ }
1800
+ }
1801
+ `;
1802
+ const variables = buildListVariables(params);
1803
+ const data = await client.execute(query, variables);
1804
+ return data.transcripts.map(normalizeTranscript);
1805
+ },
1806
+ async getSummary(id) {
1807
+ const query = `
1808
+ query GetTranscriptSummary($id: String!) {
1809
+ transcript(id: $id) {
1810
+ summary {
1811
+ action_items
1812
+ keywords
1813
+ outline
1814
+ overview
1815
+ shorthand_bullet
1816
+ notes
1817
+ gist
1818
+ bullet_gist
1819
+ short_summary
1820
+ short_overview
1821
+ meeting_type
1822
+ topics_discussed
1823
+ transcript_chapters
1824
+ extended_sections {
1825
+ title
1826
+ content
1827
+ }
1828
+ }
1829
+ }
1830
+ }
1831
+ `;
1832
+ const data = await client.execute(query, { id });
1833
+ return data.transcript.summary;
1834
+ },
1835
+ listAll(params) {
1836
+ return paginate((skip, limit) => this.list({ ...params, skip, limit }), 50);
1837
+ },
1838
+ async search(query, params = {}) {
1839
+ const {
1840
+ caseSensitive = false,
1841
+ scope = "sentences",
1842
+ speakers,
1843
+ filterQuestions,
1844
+ filterTasks,
1845
+ contextLines = 1,
1846
+ limit,
1847
+ ...listParams
1848
+ } = params;
1849
+ const transcripts = [];
1850
+ for await (const t of this.listAll({
1851
+ keyword: query,
1852
+ scope,
1853
+ ...listParams
1854
+ })) {
1855
+ transcripts.push(t);
1856
+ if (limit && transcripts.length >= limit) break;
1857
+ }
1858
+ const allMatches = [];
1859
+ let transcriptsWithMatches = 0;
1860
+ for (const t of transcripts) {
1861
+ const full = await this.get(t.id, { includeSentences: true });
1862
+ const matches = searchTranscript(full, {
1863
+ query,
1864
+ caseSensitive,
1865
+ speakers,
1866
+ filterQuestions,
1867
+ filterTasks,
1868
+ contextLines
1869
+ });
1870
+ if (matches.length > 0) {
1871
+ transcriptsWithMatches++;
1872
+ allMatches.push(...matches);
1873
+ }
1874
+ }
1875
+ return {
1876
+ query,
1877
+ options: params,
1878
+ totalMatches: allMatches.length,
1879
+ transcriptsSearched: transcripts.length,
1880
+ transcriptsWithMatches,
1881
+ matches: allMatches
1882
+ };
1883
+ },
1884
+ async insights(params = {}) {
1885
+ const {
1886
+ fromDate,
1887
+ toDate,
1888
+ mine,
1889
+ organizers,
1890
+ participants,
1891
+ user_id,
1892
+ channel_id,
1893
+ limit,
1894
+ external,
1895
+ speakers,
1896
+ groupBy: groupBy2,
1897
+ topSpeakersCount,
1898
+ topParticipantsCount
1899
+ } = params;
1900
+ let internalDomain;
1901
+ if (external) {
1902
+ const userQuery = "query { user { email } }";
1903
+ const userData = await client.execute(userQuery);
1904
+ internalDomain = extractDomain(userData.user.email);
1905
+ }
1906
+ const transcripts = [];
1907
+ for await (const t of this.listAll({
1908
+ fromDate,
1909
+ toDate,
1910
+ mine,
1911
+ organizers,
1912
+ participants,
1913
+ user_id,
1914
+ channel_id
1915
+ })) {
1916
+ if (internalDomain && !hasExternalParticipants(t.participants, internalDomain)) {
1917
+ continue;
1918
+ }
1919
+ const full = await this.get(t.id, { includeSentences: true, includeSummary: false });
1920
+ transcripts.push(full);
1921
+ if (limit && transcripts.length >= limit) break;
1922
+ }
1923
+ return analyzeMeetings(transcripts, {
1924
+ speakers,
1925
+ groupBy: groupBy2,
1926
+ topSpeakersCount,
1927
+ topParticipantsCount
1928
+ });
1929
+ },
1930
+ async exportActionItems(params = {}) {
1931
+ const { fromDate, toDate, mine, organizers, participants, limit, filterOptions } = params;
1932
+ const transcripts = [];
1933
+ for await (const t of this.listAll({
1934
+ fromDate,
1935
+ toDate,
1936
+ mine,
1937
+ organizers,
1938
+ participants
1939
+ })) {
1940
+ const full = await this.get(t.id, { includeSentences: false, includeSummary: true });
1941
+ transcripts.push(full);
1942
+ if (limit && transcripts.length >= limit) break;
1943
+ }
1944
+ return aggregateActionItems(transcripts, {}, filterOptions);
1945
+ }
1946
+ };
1947
+ }
1948
+ function orUndefined(value) {
1949
+ return value ?? void 0;
1950
+ }
1951
+ function orEmptyArray(value) {
1952
+ return value ?? [];
1953
+ }
1954
+ function normalizeRequiredFields(raw) {
1955
+ return {
1956
+ id: raw.id,
1957
+ title: raw.title ?? "",
1958
+ organizer_email: raw.organizer_email ?? "",
1959
+ transcript_url: raw.transcript_url ?? "",
1960
+ duration: raw.duration ?? 0,
1961
+ dateString: raw.dateString ?? "",
1962
+ date: raw.date ?? 0
1963
+ };
1964
+ }
1965
+ function normalizeArrayFields(raw) {
1966
+ return {
1967
+ speakers: orEmptyArray(raw.speakers),
1968
+ participants: orEmptyArray(raw.participants),
1969
+ meeting_attendees: orEmptyArray(raw.meeting_attendees),
1970
+ meeting_attendance: orEmptyArray(raw.meeting_attendance),
1971
+ fireflies_users: orEmptyArray(raw.fireflies_users),
1972
+ workspace_users: orEmptyArray(raw.workspace_users),
1973
+ sentences: orEmptyArray(raw.sentences),
1974
+ channels: orEmptyArray(raw.channels)
1975
+ };
1976
+ }
1977
+ function normalizeOptionalFields(raw) {
1978
+ return {
1979
+ host_email: orUndefined(raw.host_email),
1980
+ user: orUndefined(raw.user),
1981
+ audio_url: orUndefined(raw.audio_url),
1982
+ video_url: orUndefined(raw.video_url),
1983
+ calendar_id: orUndefined(raw.calendar_id),
1984
+ summary: orUndefined(raw.summary),
1985
+ meeting_info: orUndefined(raw.meeting_info),
1986
+ cal_id: orUndefined(raw.cal_id),
1987
+ calendar_type: orUndefined(raw.calendar_type),
1988
+ apps_preview: orUndefined(raw.apps_preview),
1989
+ meeting_link: orUndefined(raw.meeting_link),
1990
+ analytics: orUndefined(raw.analytics)
1991
+ };
1992
+ }
1993
+ function normalizeTranscript(raw) {
1994
+ return {
1995
+ ...normalizeRequiredFields(raw),
1996
+ ...normalizeArrayFields(raw),
1997
+ ...normalizeOptionalFields(raw)
1998
+ };
1999
+ }
2000
+ function buildListVariables(params) {
2001
+ if (!params) {
2002
+ return { limit: 50 };
2003
+ }
2004
+ return {
2005
+ keyword: params.keyword,
2006
+ scope: params.scope,
2007
+ organizers: params.organizers,
2008
+ participants: params.participants,
2009
+ user_id: params.user_id,
2010
+ mine: params.mine,
2011
+ channel_id: params.channel_id,
2012
+ fromDate: params.fromDate,
2013
+ toDate: params.toDate,
2014
+ limit: params.limit ?? 50,
2015
+ skip: params.skip,
2016
+ title: params.title,
2017
+ host_email: params.host_email,
2018
+ organizer_email: params.organizer_email,
2019
+ participant_email: params.participant_email,
2020
+ date: params.date
2021
+ };
2022
+ }
2023
+
2024
+ // src/graphql/queries/users.ts
2025
+ var USER_FIELDS = `
2026
+ user_id
2027
+ email
2028
+ name
2029
+ num_transcripts
2030
+ recent_meeting
2031
+ recent_transcript
2032
+ minutes_consumed
2033
+ is_admin
2034
+ integrations
2035
+ user_groups {
2036
+ id
2037
+ name
2038
+ handle
2039
+ members {
2040
+ user_id
2041
+ email
2042
+ }
2043
+ }
2044
+ `;
2045
+ function createUsersAPI(client) {
2046
+ return {
2047
+ async me() {
2048
+ const query = `query { user { ${USER_FIELDS} } }`;
2049
+ const data = await client.execute(query);
2050
+ return data.user;
2051
+ },
2052
+ async get(id) {
2053
+ const query = `
2054
+ query User($userId: String!) {
2055
+ user(id: $userId) { ${USER_FIELDS} }
2056
+ }
2057
+ `;
2058
+ const data = await client.execute(query, { userId: id });
2059
+ return data.user;
2060
+ },
2061
+ async list() {
2062
+ const query = `query Users { users { ${USER_FIELDS} } }`;
2063
+ const data = await client.execute(query);
2064
+ return data.users;
2065
+ }
2066
+ };
2067
+ }
2068
+ var DEFAULT_WS_URL = "wss://api.fireflies.ai";
2069
+ var DEFAULT_WS_PATH = "/ws/realtime";
2070
+ var DEFAULT_TIMEOUT2 = 2e4;
2071
+ var DEFAULT_CHUNK_TIMEOUT = 2e4;
2072
+ var DEFAULT_RECONNECT_DELAY = 5e3;
2073
+ var DEFAULT_MAX_RECONNECT_DELAY = 6e4;
2074
+ var DEFAULT_MAX_RECONNECT_ATTEMPTS = 10;
2075
+ var RealtimeConnection = class {
2076
+ socket = null;
2077
+ config;
2078
+ constructor(config) {
2079
+ this.config = {
2080
+ wsUrl: DEFAULT_WS_URL,
2081
+ wsPath: DEFAULT_WS_PATH,
2082
+ timeout: DEFAULT_TIMEOUT2,
2083
+ chunkTimeout: DEFAULT_CHUNK_TIMEOUT,
2084
+ reconnect: true,
2085
+ maxReconnectAttempts: DEFAULT_MAX_RECONNECT_ATTEMPTS,
2086
+ reconnectDelay: DEFAULT_RECONNECT_DELAY,
2087
+ maxReconnectDelay: DEFAULT_MAX_RECONNECT_DELAY,
2088
+ ...config
2089
+ };
2090
+ }
2091
+ /**
2092
+ * Establish connection and wait for auth success.
2093
+ */
2094
+ async connect() {
2095
+ if (this.socket?.connected) {
2096
+ return;
2097
+ }
2098
+ const socket = io(this.config.wsUrl, {
2099
+ path: this.config.wsPath,
2100
+ auth: {
2101
+ token: `Bearer ${this.config.apiKey}`,
2102
+ transcriptId: this.config.transcriptId
2103
+ },
2104
+ // Force WebSocket transport (proven more reliable than polling)
2105
+ transports: ["websocket"],
2106
+ reconnection: this.config.reconnect,
2107
+ reconnectionDelay: this.config.reconnectDelay,
2108
+ reconnectionDelayMax: this.config.maxReconnectDelay,
2109
+ reconnectionAttempts: this.config.maxReconnectAttempts,
2110
+ // Exponential backoff factor (default 2x matches our fireflies-whiteboard pattern)
2111
+ randomizationFactor: 0.5,
2112
+ timeout: this.config.timeout,
2113
+ autoConnect: false
2114
+ });
2115
+ this.socket = socket;
2116
+ return new Promise((resolve, reject) => {
2117
+ const timeoutId = setTimeout(() => {
2118
+ socket.disconnect();
2119
+ reject(new TimeoutError(`Realtime connection timed out after ${this.config.timeout}ms`));
2120
+ }, this.config.timeout);
2121
+ const cleanup = () => clearTimeout(timeoutId);
2122
+ socket.once("auth.success", () => {
2123
+ cleanup();
2124
+ resolve();
2125
+ });
2126
+ socket.once("auth.failed", (data) => {
2127
+ cleanup();
2128
+ socket.disconnect();
2129
+ reject(new AuthenticationError(`Realtime auth failed: ${formatData(data)}`));
2130
+ });
2131
+ socket.once("connection.error", (data) => {
2132
+ cleanup();
2133
+ socket.disconnect();
2134
+ reject(new ConnectionError(`Realtime connection error: ${formatData(data)}`));
2135
+ });
2136
+ socket.once("connect_error", (error) => {
2137
+ cleanup();
2138
+ socket.disconnect();
2139
+ const message = error.message || "Connection failed";
2140
+ if (message.includes("auth") || message.includes("401") || message.includes("unauthorized")) {
2141
+ reject(new AuthenticationError(`Realtime auth failed: ${message}`));
2142
+ } else {
2143
+ reject(
2144
+ new ConnectionError(`Realtime connection failed: ${message}`, {
2145
+ cause: error
2146
+ })
2147
+ );
2148
+ }
2149
+ });
2150
+ socket.connect();
2151
+ });
2152
+ }
2153
+ /**
2154
+ * Register a chunk handler.
2155
+ * Handles both { payload: {...} } and direct payload shapes.
2156
+ */
2157
+ onChunk(handler) {
2158
+ this.socket?.on("transcription.broadcast", (data) => {
2159
+ const chunk = "payload" in data ? data.payload : data;
2160
+ handler(chunk);
2161
+ });
2162
+ }
2163
+ /**
2164
+ * Register a disconnect handler.
2165
+ */
2166
+ onDisconnect(handler) {
2167
+ this.socket?.on("disconnect", handler);
2168
+ }
2169
+ /**
2170
+ * Register a reconnect handler.
2171
+ */
2172
+ onReconnect(handler) {
2173
+ this.socket?.io.on("reconnect", handler);
2174
+ }
2175
+ /**
2176
+ * Register a reconnect attempt handler.
2177
+ */
2178
+ onReconnectAttempt(handler) {
2179
+ this.socket?.io.on("reconnect_attempt", handler);
2180
+ }
2181
+ /**
2182
+ * Register an error handler.
2183
+ */
2184
+ onError(handler) {
2185
+ this.socket?.on("connect_error", handler);
2186
+ }
2187
+ /**
2188
+ * Disconnect and cleanup.
2189
+ */
2190
+ disconnect() {
2191
+ if (this.socket) {
2192
+ this.socket.disconnect();
2193
+ this.socket = null;
2194
+ }
2195
+ }
2196
+ get connected() {
2197
+ return this.socket?.connected ?? false;
2198
+ }
2199
+ };
2200
+ function formatData(data) {
2201
+ if (data === void 0 || data === null) {
2202
+ return String(data);
2203
+ }
2204
+ try {
2205
+ return JSON.stringify(data);
2206
+ } catch {
2207
+ return String(data);
2208
+ }
2209
+ }
2210
+
2211
+ // src/realtime/stream.ts
2212
+ var RealtimeStream = class {
2213
+ connection;
2214
+ listeners = /* @__PURE__ */ new Map();
2215
+ buffer = [];
2216
+ waiters = [];
2217
+ closed = false;
2218
+ lastChunkId = null;
2219
+ lastChunk = null;
2220
+ constructor(config) {
2221
+ this.connection = new RealtimeConnection(config);
2222
+ }
2223
+ /**
2224
+ * Connect to the realtime stream.
2225
+ * @throws AuthenticationError if authentication fails
2226
+ * @throws ConnectionError if connection fails
2227
+ * @throws TimeoutError if connection times out
2228
+ */
2229
+ async connect() {
2230
+ await this.connection.connect();
2231
+ this.setupHandlers();
2232
+ this.emit("connected");
2233
+ }
2234
+ setupHandlers() {
2235
+ this.connection.onChunk((rawChunk) => {
2236
+ const isNewChunk = this.lastChunkId !== null && rawChunk.chunk_id !== this.lastChunkId;
2237
+ if (isNewChunk && this.lastChunk) {
2238
+ const finalChunk = { ...this.lastChunk, isFinal: true };
2239
+ this.emitChunk(finalChunk);
2240
+ }
2241
+ const chunk = { ...rawChunk, isFinal: false };
2242
+ this.lastChunkId = chunk.chunk_id;
2243
+ this.lastChunk = chunk;
2244
+ this.emit("chunk", chunk);
2245
+ });
2246
+ this.connection.onDisconnect((reason) => {
2247
+ if (this.lastChunk) {
2248
+ const finalChunk = { ...this.lastChunk, isFinal: true };
2249
+ this.emitChunk(finalChunk);
2250
+ this.lastChunk = null;
2251
+ }
2252
+ this.emit("disconnected", reason);
2253
+ if (!this.connection.connected) {
2254
+ this.closed = true;
2255
+ for (const waiter of this.waiters) {
2256
+ waiter(null);
2257
+ }
2258
+ this.waiters = [];
2259
+ }
2260
+ });
2261
+ this.connection.onReconnectAttempt((attempt) => {
2262
+ this.emit("reconnecting", attempt);
2263
+ });
2264
+ this.connection.onReconnect(() => {
2265
+ this.emit("connected");
2266
+ });
2267
+ this.connection.onError((error) => {
2268
+ this.emit("error", error);
2269
+ });
2270
+ }
2271
+ /**
2272
+ * Register an event listener.
2273
+ * @param event - Event name
2274
+ * @param handler - Event handler
2275
+ */
2276
+ on(event, handler) {
2277
+ let handlers = this.listeners.get(event);
2278
+ if (!handlers) {
2279
+ handlers = /* @__PURE__ */ new Set();
2280
+ this.listeners.set(event, handlers);
2281
+ }
2282
+ handlers.add(handler);
2283
+ return this;
2284
+ }
2285
+ /**
2286
+ * Remove an event listener.
2287
+ * @param event - Event name
2288
+ * @param handler - Event handler to remove
2289
+ */
2290
+ off(event, handler) {
2291
+ this.listeners.get(event)?.delete(handler);
2292
+ return this;
2293
+ }
2294
+ /**
2295
+ * Emit a chunk to both event listeners and async iterator buffer.
2296
+ * Used for final chunks that should be yielded by the iterator.
2297
+ */
2298
+ emitChunk(chunk) {
2299
+ this.emit("chunk", chunk);
2300
+ if (chunk.isFinal) {
2301
+ if (this.waiters.length > 0) {
2302
+ const waiter = this.waiters.shift();
2303
+ waiter?.(chunk);
2304
+ } else {
2305
+ this.buffer.push(chunk);
2306
+ }
2307
+ }
2308
+ }
2309
+ emit(event, ...args) {
2310
+ const handlers = this.listeners.get(event);
2311
+ handlers?.forEach((handler) => {
2312
+ try {
2313
+ handler(...args);
2314
+ } catch {
2315
+ }
2316
+ });
2317
+ }
2318
+ /**
2319
+ * AsyncIterable implementation for `for await` loops.
2320
+ */
2321
+ async *[Symbol.asyncIterator]() {
2322
+ if (this.closed) {
2323
+ throw new StreamClosedError();
2324
+ }
2325
+ while (!this.closed) {
2326
+ const buffered = this.buffer.shift();
2327
+ if (buffered) {
2328
+ yield buffered;
2329
+ continue;
2330
+ }
2331
+ const chunk = await new Promise((resolve) => {
2332
+ if (this.closed) {
2333
+ resolve(null);
2334
+ return;
2335
+ }
2336
+ this.waiters.push(resolve);
2337
+ });
2338
+ if (chunk === null) {
2339
+ break;
2340
+ }
2341
+ yield chunk;
2342
+ }
2343
+ }
2344
+ /**
2345
+ * Close the stream and disconnect.
2346
+ */
2347
+ close() {
2348
+ if (this.lastChunk) {
2349
+ const finalChunk = { ...this.lastChunk, isFinal: true };
2350
+ this.emitChunk(finalChunk);
2351
+ this.lastChunk = null;
2352
+ }
2353
+ this.closed = true;
2354
+ this.connection.disconnect();
2355
+ this.buffer = [];
2356
+ this.lastChunkId = null;
2357
+ for (const waiter of this.waiters) {
2358
+ waiter(null);
2359
+ }
2360
+ this.waiters = [];
2361
+ }
2362
+ /**
2363
+ * Whether the stream is currently connected.
2364
+ */
2365
+ get connected() {
2366
+ return this.connection.connected;
2367
+ }
2368
+ };
2369
+
2370
+ // src/realtime/api.ts
2371
+ function createRealtimeAPI(apiKey, baseConfig) {
2372
+ return {
2373
+ async connect(transcriptId) {
2374
+ const stream = new RealtimeStream({
2375
+ apiKey,
2376
+ transcriptId,
2377
+ ...baseConfig
2378
+ });
2379
+ await stream.connect();
2380
+ return stream;
2381
+ },
2382
+ async *stream(transcriptId) {
2383
+ const stream = new RealtimeStream({
2384
+ apiKey,
2385
+ transcriptId,
2386
+ ...baseConfig
2387
+ });
2388
+ try {
2389
+ await stream.connect();
2390
+ yield* stream;
2391
+ } finally {
2392
+ stream.close();
2393
+ }
2394
+ }
2395
+ };
2396
+ }
2397
+
2398
+ // src/client.ts
2399
+ var FirefliesClient = class {
2400
+ graphql;
2401
+ /**
2402
+ * Transcript operations: list, get, search, delete.
2403
+ */
2404
+ transcripts;
2405
+ /**
2406
+ * User operations: me, get, list, setRole.
2407
+ */
2408
+ users;
2409
+ /**
2410
+ * Bite operations: get, list, create.
2411
+ */
2412
+ bites;
2413
+ /**
2414
+ * Meeting operations: active meetings, add bot.
2415
+ */
2416
+ meetings;
2417
+ /**
2418
+ * Audio operations: upload audio for transcription.
2419
+ */
2420
+ audio;
2421
+ /**
2422
+ * AI Apps operations: list outputs.
2423
+ */
2424
+ aiApps;
2425
+ /**
2426
+ * Realtime transcription streaming.
2427
+ */
2428
+ realtime;
2429
+ /**
2430
+ * Create a new Fireflies client.
2431
+ *
2432
+ * @param config - Client configuration
2433
+ * @throws FirefliesError if API key is missing
2434
+ */
2435
+ constructor(config) {
2436
+ this.graphql = new GraphQLClient(config);
2437
+ const transcriptsQueries = createTranscriptsAPI(this.graphql);
2438
+ const transcriptsMutations = createTranscriptsMutationsAPI(this.graphql);
2439
+ this.transcripts = { ...transcriptsQueries, ...transcriptsMutations };
2440
+ const usersQueries = createUsersAPI(this.graphql);
2441
+ const usersMutations = createUsersMutationsAPI(this.graphql);
2442
+ this.users = { ...usersQueries, ...usersMutations };
2443
+ this.bites = createBitesAPI(this.graphql);
2444
+ this.meetings = createMeetingsAPI(this.graphql);
2445
+ this.audio = createAudioAPI(this.graphql);
2446
+ this.aiApps = createAIAppsAPI(this.graphql);
2447
+ this.realtime = createRealtimeAPI(config.apiKey);
2448
+ }
2449
+ /**
2450
+ * Get the current rate limit state.
2451
+ * Returns undefined if rate limit tracking is not configured.
2452
+ *
2453
+ * @example
2454
+ * ```typescript
2455
+ * const client = new FirefliesClient({
2456
+ * apiKey: '...',
2457
+ * rateLimit: { warningThreshold: 10 }
2458
+ * });
2459
+ *
2460
+ * await client.users.me();
2461
+ * console.log(client.rateLimits);
2462
+ * // { remaining: 59, limit: 60, resetInSeconds: 60, updatedAt: 1706299500000 }
2463
+ * ```
2464
+ */
2465
+ get rateLimits() {
2466
+ return this.graphql.rateLimitState;
2467
+ }
2468
+ };
2469
+
2470
+ // src/helpers/accumulator.ts
2471
+ var TranscriptAccumulator = class {
2472
+ turns = [];
2473
+ currentTurn = null;
2474
+ seenChunkIds = /* @__PURE__ */ new Set();
2475
+ /**
2476
+ * Add a chunk to the accumulator.
2477
+ *
2478
+ * Only final chunks are accumulated; non-final chunks are ignored.
2479
+ * Duplicate chunk IDs are also ignored.
2480
+ *
2481
+ * @param chunk - The transcription chunk to add
2482
+ */
2483
+ add(chunk) {
2484
+ if (!chunk.isFinal) return;
2485
+ if (this.seenChunkIds.has(chunk.chunk_id)) return;
2486
+ this.seenChunkIds.add(chunk.chunk_id);
2487
+ if (this.currentTurn && this.currentTurn.speaker === chunk.speaker_name) {
2488
+ this.currentTurn.text += ` ${chunk.text}`;
2489
+ this.currentTurn.endTime = chunk.end_time;
2490
+ this.currentTurn.chunks.push(chunk);
2491
+ } else {
2492
+ this.currentTurn = {
2493
+ speaker: chunk.speaker_name,
2494
+ text: chunk.text,
2495
+ startTime: chunk.start_time,
2496
+ endTime: chunk.end_time,
2497
+ chunks: [chunk]
2498
+ };
2499
+ this.turns.push(this.currentTurn);
2500
+ }
2501
+ }
2502
+ /**
2503
+ * Get the current accumulated transcript state.
2504
+ *
2505
+ * Statistics are computed on demand to ensure accuracy.
2506
+ *
2507
+ * @returns The accumulated transcript with turns, speakers, and statistics
2508
+ */
2509
+ getTranscript() {
2510
+ const speakers = this.getUniqueSpeakers();
2511
+ const wordCount = this.computeWordCount();
2512
+ const duration = this.computeDuration();
2513
+ return {
2514
+ turns: this.turns,
2515
+ speakers,
2516
+ wordCount,
2517
+ duration,
2518
+ chunkCount: this.seenChunkIds.size
2519
+ };
2520
+ }
2521
+ /**
2522
+ * Clear all accumulated data.
2523
+ *
2524
+ * Useful for resetting the accumulator between sessions.
2525
+ */
2526
+ clear() {
2527
+ this.turns = [];
2528
+ this.currentTurn = null;
2529
+ this.seenChunkIds.clear();
2530
+ }
2531
+ getUniqueSpeakers() {
2532
+ const seen = /* @__PURE__ */ new Set();
2533
+ const speakers = [];
2534
+ for (const turn of this.turns) {
2535
+ if (!seen.has(turn.speaker)) {
2536
+ seen.add(turn.speaker);
2537
+ speakers.push(turn.speaker);
2538
+ }
2539
+ }
2540
+ return speakers;
2541
+ }
2542
+ computeWordCount() {
2543
+ let count = 0;
2544
+ for (const turn of this.turns) {
2545
+ if (turn.text.length === 0) continue;
2546
+ const words = turn.text.trim().split(/\s+/);
2547
+ count += words.filter((w) => w.length > 0).length;
2548
+ }
2549
+ return count;
2550
+ }
2551
+ computeDuration() {
2552
+ const firstTurn = this.turns[0];
2553
+ const lastTurn = this.turns[this.turns.length - 1];
2554
+ if (!firstTurn || !lastTurn) return 0;
2555
+ const firstChunk = firstTurn.chunks[0];
2556
+ if (!firstChunk) return 0;
2557
+ return lastTurn.endTime - firstChunk.start_time;
2558
+ }
2559
+ };
2560
+
2561
+ // src/helpers/batch.ts
2562
+ async function* batch(items, processor, options = {}) {
2563
+ const { delayMs = 100, handleRateLimit = true, maxRateLimitRetries = 3 } = options;
2564
+ let isFirst = true;
2565
+ for await (const item of items) {
2566
+ if (!isFirst && delayMs > 0) {
2567
+ await delay(delayMs);
2568
+ }
2569
+ isFirst = false;
2570
+ yield await processWithRetry(item, processor, {
2571
+ handleRateLimit,
2572
+ maxRateLimitRetries
2573
+ });
2574
+ }
2575
+ }
2576
+ async function batchAll(items, processor, options = {}) {
2577
+ const { continueOnError = false, ...batchOptions } = options;
2578
+ const results = [];
2579
+ const errors = [];
2580
+ for await (const batchResult of batch(items, processor, batchOptions)) {
2581
+ if (batchResult.error) {
2582
+ if (!continueOnError) {
2583
+ throw batchResult.error;
2584
+ }
2585
+ errors.push(batchResult.error);
2586
+ } else {
2587
+ results.push(batchResult.result);
2588
+ }
2589
+ }
2590
+ return results;
2591
+ }
2592
+ async function processWithRetry(item, processor, options) {
2593
+ const { handleRateLimit, maxRateLimitRetries } = options;
2594
+ let retries = 0;
2595
+ while (true) {
2596
+ try {
2597
+ const result = await processor(item);
2598
+ return { item, result };
2599
+ } catch (err) {
2600
+ if (handleRateLimit && err instanceof RateLimitError && retries < maxRateLimitRetries) {
2601
+ const waitTime = err.retryAfter ?? 1e3;
2602
+ await delay(waitTime);
2603
+ retries++;
2604
+ continue;
2605
+ }
2606
+ return {
2607
+ item,
2608
+ error: err instanceof Error ? err : new Error(String(err))
2609
+ };
2610
+ }
2611
+ }
2612
+ }
2613
+ function delay(ms) {
2614
+ return new Promise((resolve) => setTimeout(resolve, ms));
2615
+ }
2616
+
2617
+ // src/helpers/external-questions.ts
2618
+ function findExternalParticipantQuestions(transcript, internalDomains) {
2619
+ const domains = normalizeDomains(internalDomains);
2620
+ const speakerEmailMap = buildSpeakerEmailMap(transcript);
2621
+ const { externalSpeakers } = classifySpeakers(transcript, speakerEmailMap, domains);
2622
+ const questions = [];
2623
+ for (const sentence of transcript.sentences ?? []) {
2624
+ if (!sentence.ai_filters?.question) {
2625
+ continue;
2626
+ }
2627
+ if (!externalSpeakers.has(sentence.speaker_name)) {
2628
+ continue;
2629
+ }
2630
+ questions.push({
2631
+ text: sentence.text,
2632
+ speakerName: sentence.speaker_name,
2633
+ speakerEmail: speakerEmailMap.get(sentence.speaker_name),
2634
+ sentenceIndex: sentence.index,
2635
+ startTime: sentence.start_time,
2636
+ endTime: sentence.end_time
2637
+ });
2638
+ }
2639
+ const externalParticipants = Array.from(externalSpeakers).map((name) => ({
2640
+ name,
2641
+ email: speakerEmailMap.get(name)
2642
+ }));
2643
+ return {
2644
+ externalParticipants,
2645
+ questions,
2646
+ totalQuestions: questions.length
2647
+ };
2648
+ }
2649
+ function normalizeDomains(input) {
2650
+ const raw = Array.isArray(input) ? input : [input];
2651
+ return raw.map((d) => {
2652
+ const domain = d.toLowerCase().trim();
2653
+ return domain.startsWith("@") ? domain : `@${domain}`;
2654
+ });
2655
+ }
2656
+ function buildSpeakerEmailMap(transcript) {
2657
+ const map = /* @__PURE__ */ new Map();
2658
+ for (const attendee of transcript.meeting_attendees ?? []) {
2659
+ if (attendee.displayName && attendee.email) {
2660
+ map.set(attendee.displayName, attendee.email.toLowerCase());
2661
+ }
2662
+ if (attendee.name && attendee.email) {
2663
+ map.set(attendee.name, attendee.email.toLowerCase());
2664
+ }
2665
+ }
2666
+ return map;
2667
+ }
2668
+ function classifySpeakers(transcript, speakerEmailMap, internalDomains) {
2669
+ const internalSpeakers = /* @__PURE__ */ new Set();
2670
+ const externalSpeakers = /* @__PURE__ */ new Set();
2671
+ const speakerNames = new Set((transcript.sentences ?? []).map((s) => s.speaker_name));
2672
+ for (const name of speakerNames) {
2673
+ const email = speakerEmailMap.get(name);
2674
+ if (isInternal(email, internalDomains)) {
2675
+ internalSpeakers.add(name);
2676
+ } else {
2677
+ externalSpeakers.add(name);
2678
+ }
2679
+ }
2680
+ return { internalSpeakers, externalSpeakers };
2681
+ }
2682
+ function isInternal(email, internalDomains) {
2683
+ if (!email) {
2684
+ return false;
2685
+ }
2686
+ const lowerEmail = email.toLowerCase();
2687
+ return internalDomains.some((domain) => lowerEmail.endsWith(domain));
2688
+ }
2689
+
2690
+ // src/helpers/markdown.ts
2691
+ var DEFAULT_OPTIONS2 = {
2692
+ includeMetadata: true,
2693
+ includeSummary: true,
2694
+ includeActionItems: true,
2695
+ actionItemFormat: "checkbox",
2696
+ includeTimestamps: false,
2697
+ speakerFormat: "bold",
2698
+ groupBySpeaker: true
2699
+ };
2700
+ var DEFAULT_CHUNKS_OPTIONS = {
2701
+ title: "Live Transcript",
2702
+ includeTimestamps: false,
2703
+ speakerFormat: "bold",
2704
+ groupBySpeaker: true
2705
+ };
2706
+ async function transcriptToMarkdown(transcript, options = {}) {
2707
+ const opts = { ...DEFAULT_OPTIONS2, ...options };
2708
+ const sections = [];
2709
+ if (opts.includeMetadata) {
2710
+ sections.push(formatMetadata(transcript));
2711
+ }
2712
+ if (opts.includeSummary && transcript.summary) {
2713
+ sections.push(formatSummary(transcript.summary, opts));
2714
+ }
2715
+ if (transcript.sentences && transcript.sentences.length > 0) {
2716
+ sections.push(formatTranscript(transcript.sentences, opts));
2717
+ }
2718
+ const content = sections.join("\n\n---\n\n");
2719
+ await writeIfOutputPath(content, options.outputPath);
2720
+ return content;
2721
+ }
2722
+ async function chunksToMarkdown(chunks, options = {}) {
2723
+ const opts = { ...DEFAULT_CHUNKS_OPTIONS, ...options };
2724
+ const lines = [`# ${opts.title}`];
2725
+ if (chunks.length === 0) {
2726
+ lines.push("", "## Transcript", "", "*No transcription data*");
2727
+ } else {
2728
+ lines.push("", "## Transcript");
2729
+ if (opts.groupBySpeaker) {
2730
+ const groups = groupChunksBySpeaker(chunks);
2731
+ for (const group of groups) {
2732
+ lines.push("", formatChunkGroup(group, opts));
2733
+ }
2734
+ } else {
2735
+ for (const chunk of chunks) {
2736
+ lines.push("", formatChunk(chunk, opts));
2737
+ }
2738
+ }
2739
+ }
2740
+ const content = lines.join("\n");
2741
+ await writeIfOutputPath(content, options.outputPath);
2742
+ return content;
2743
+ }
2744
+ function formatMetadata(transcript) {
2745
+ const lines = [`# ${transcript.title || "Untitled Meeting"}`];
2746
+ if (transcript.dateString) {
2747
+ lines.push(`
2748
+ **Date:** ${formatDate(transcript.dateString)}`);
2749
+ }
2750
+ const duration = calculateDuration(transcript);
2751
+ if (duration > 0) {
2752
+ lines.push(`**Duration:** ${formatDuration(duration)}`);
2753
+ }
2754
+ const participants = getParticipantNames(transcript);
2755
+ if (participants.length > 0) {
2756
+ lines.push(`**Participants:** ${participants.join(", ")}`);
2757
+ }
2758
+ return lines.join("\n");
2759
+ }
2760
+ function calculateDuration(transcript) {
2761
+ if (transcript.sentences && transcript.sentences.length > 0) {
2762
+ const lastSentence = transcript.sentences[transcript.sentences.length - 1];
2763
+ if (lastSentence) {
2764
+ return parseFloat(lastSentence.end_time);
2765
+ }
2766
+ }
2767
+ return transcript.duration || 0;
2768
+ }
2769
+ function formatSummary(summary, opts) {
2770
+ const sections = ["## Summary"];
2771
+ if (summary.gist) {
2772
+ sections.push("", summary.gist);
2773
+ }
2774
+ if (summary.bullet_gist) {
2775
+ const bullets = parseMultilineField(summary.bullet_gist);
2776
+ if (bullets.length > 0) {
2777
+ sections.push("", "### Key Points");
2778
+ sections.push(bullets.map((p) => `- ${p}`).join("\n"));
2779
+ }
2780
+ }
2781
+ if (opts.includeActionItems && summary.action_items) {
2782
+ const items = parseMultilineField(summary.action_items);
2783
+ if (items.length > 0) {
2784
+ sections.push("", "### Action Items");
2785
+ const prefix = opts.actionItemFormat === "checkbox" ? "- [ ] " : "- ";
2786
+ sections.push(items.map((a) => `${prefix}${a}`).join("\n"));
2787
+ }
2788
+ }
2789
+ return sections.join("\n");
2790
+ }
2791
+ function formatTranscript(sentences, opts) {
2792
+ const lines = ["## Transcript"];
2793
+ if (opts.groupBySpeaker) {
2794
+ const groups = groupSentencesBySpeaker(sentences);
2795
+ for (const group of groups) {
2796
+ lines.push("", formatSpeakerGroup(group, opts));
2797
+ }
2798
+ } else {
2799
+ for (const sentence of sentences) {
2800
+ lines.push("", formatSentence(sentence, opts));
2801
+ }
2802
+ }
2803
+ return lines.join("\n");
2804
+ }
2805
+ function groupSentencesBySpeaker(sentences) {
2806
+ const groups = [];
2807
+ let current = null;
2808
+ for (const sentence of sentences) {
2809
+ if (!current || current.speakerName !== sentence.speaker_name) {
2810
+ current = { speakerName: sentence.speaker_name, sentences: [] };
2811
+ groups.push(current);
2812
+ }
2813
+ current.sentences.push(sentence);
2814
+ }
2815
+ return groups;
2816
+ }
2817
+ function formatSpeakerGroup(group, opts) {
2818
+ const speaker = formatSpeakerName(group.speakerName, opts.speakerFormat);
2819
+ const text = group.sentences.map((s) => s.text).join(" ");
2820
+ const firstSentence = group.sentences[0];
2821
+ if (opts.includeTimestamps && firstSentence) {
2822
+ const timestamp = formatTimestamp(firstSentence.start_time);
2823
+ return `${timestamp} ${speaker} ${text}`;
2824
+ }
2825
+ return `${speaker} ${text}`;
2826
+ }
2827
+ function formatSentence(sentence, opts) {
2828
+ const speaker = formatSpeakerName(sentence.speaker_name, opts.speakerFormat);
2829
+ if (opts.includeTimestamps) {
2830
+ const timestamp = formatTimestamp(sentence.start_time);
2831
+ return `${timestamp} ${speaker} ${sentence.text}`;
2832
+ }
2833
+ return `${speaker} ${sentence.text}`;
2834
+ }
2835
+ function groupChunksBySpeaker(chunks) {
2836
+ const groups = [];
2837
+ let current = null;
2838
+ for (const chunk of chunks) {
2839
+ if (!current || current.speakerName !== chunk.speaker_name) {
2840
+ current = { speakerName: chunk.speaker_name, chunks: [] };
2841
+ groups.push(current);
2842
+ }
2843
+ current.chunks.push(chunk);
2844
+ }
2845
+ return groups;
2846
+ }
2847
+ function formatChunkGroup(group, opts) {
2848
+ const speaker = formatSpeakerName(group.speakerName, opts.speakerFormat);
2849
+ const text = group.chunks.map((c) => c.text).join(" ");
2850
+ const firstChunk = group.chunks[0];
2851
+ if (opts.includeTimestamps && firstChunk) {
2852
+ const timestamp = formatTimestamp(firstChunk.start_time.toString());
2853
+ return `${timestamp} ${speaker} ${text}`;
2854
+ }
2855
+ return `${speaker} ${text}`;
2856
+ }
2857
+ function formatChunk(chunk, opts) {
2858
+ const speaker = formatSpeakerName(chunk.speaker_name, opts.speakerFormat);
2859
+ if (opts.includeTimestamps) {
2860
+ const timestamp = formatTimestamp(chunk.start_time.toString());
2861
+ return `${timestamp} ${speaker} ${chunk.text}`;
2862
+ }
2863
+ return `${speaker} ${chunk.text}`;
2864
+ }
2865
+ function formatSpeakerName(name, format) {
2866
+ switch (format) {
2867
+ case "bold":
2868
+ return `**${name}:**`;
2869
+ case "plain":
2870
+ return `${name}:`;
2871
+ }
2872
+ }
2873
+ function formatTimestamp(startTime) {
2874
+ const seconds = parseFloat(startTime);
2875
+ const mins = Math.floor(seconds / 60);
2876
+ const secs = Math.floor(seconds % 60);
2877
+ return `[${mins}:${secs.toString().padStart(2, "0")}]`;
2878
+ }
2879
+ function formatDuration(seconds) {
2880
+ const hours = Math.floor(seconds / 3600);
2881
+ const mins = Math.floor(seconds % 3600 / 60);
2882
+ if (hours > 0) {
2883
+ return `${hours}h ${mins}m`;
2884
+ }
2885
+ return `${mins} minutes`;
2886
+ }
2887
+ function formatDate(isoString) {
2888
+ return new Date(isoString).toLocaleDateString("en-US", {
2889
+ weekday: "long",
2890
+ year: "numeric",
2891
+ month: "long",
2892
+ day: "numeric"
2893
+ });
2894
+ }
2895
+ function getParticipantNames(transcript) {
2896
+ if (transcript.meeting_attendees?.length) {
2897
+ return transcript.meeting_attendees.map((a) => a.displayName || a.name || a.email).filter(Boolean);
2898
+ }
2899
+ return transcript.speakers?.map((s) => s.name) || [];
2900
+ }
2901
+ function parseMultilineField(value) {
2902
+ return value.split(/\n/).map((line) => line.trim()).filter((line) => line.length > 0);
2903
+ }
2904
+ async function writeIfOutputPath(content, outputPath) {
2905
+ if (outputPath) {
2906
+ const { writeFile } = await import('fs/promises');
2907
+ await writeFile(outputPath, content, "utf-8");
2908
+ }
2909
+ }
2910
+
2911
+ // src/utils/dedup.ts
2912
+ var Deduplicator = class {
2913
+ seen = /* @__PURE__ */ new Set();
2914
+ queue = [];
2915
+ maxSize;
2916
+ constructor(maxSize = 1e3) {
2917
+ this.maxSize = maxSize;
2918
+ }
2919
+ /**
2920
+ * Check if item is a duplicate and mark as seen.
2921
+ * @param key - Unique key to check
2922
+ * @returns true if duplicate, false if new
2923
+ */
2924
+ isDuplicate(key) {
2925
+ if (this.seen.has(key)) {
2926
+ return true;
2927
+ }
2928
+ this.seen.add(key);
2929
+ this.queue.push(key);
2930
+ while (this.queue.length > this.maxSize) {
2931
+ const oldest = this.queue.shift();
2932
+ if (oldest) this.seen.delete(oldest);
2933
+ }
2934
+ return false;
2935
+ }
2936
+ /**
2937
+ * Clear all tracked keys.
2938
+ */
2939
+ clear() {
2940
+ this.seen.clear();
2941
+ this.queue = [];
2942
+ }
2943
+ /**
2944
+ * Get current number of tracked keys.
2945
+ */
2946
+ get size() {
2947
+ return this.seen.size;
2948
+ }
2949
+ };
2950
+
2951
+ // src/helpers/multi-user.ts
2952
+ async function* getMeetingsForMultipleUsers(apiKeys, options = {}) {
2953
+ const { deduplicate = true, filter, delayMs = 100 } = options;
2954
+ const dedup = deduplicate ? new Deduplicator() : null;
2955
+ let needsDelay = false;
2956
+ for (const [sourceIndex, apiKey] of apiKeys.entries()) {
2957
+ const client = new FirefliesClient({ apiKey });
2958
+ for await (const transcript of client.transcripts.listAll(filter)) {
2959
+ if (needsDelay && delayMs > 0) {
2960
+ await delay2(delayMs);
2961
+ }
2962
+ needsDelay = true;
2963
+ if (dedup?.isDuplicate(transcript.id)) {
2964
+ continue;
2965
+ }
2966
+ yield {
2967
+ transcript,
2968
+ sourceApiKey: apiKey,
2969
+ sourceIndex
2970
+ };
2971
+ }
2972
+ }
2973
+ }
2974
+ function delay2(ms) {
2975
+ return new Promise((resolve) => setTimeout(resolve, ms));
2976
+ }
2977
+
2978
+ // src/helpers/normalize.ts
2979
+ var DEFAULT_OPTIONS3 = {
2980
+ timeUnit: "seconds",
2981
+ includeRawData: false,
2982
+ includeAIFilters: true,
2983
+ includeSummary: true,
2984
+ resolveSpeakerName: (speaker) => speaker.name,
2985
+ enrichParticipant: () => ({})
2986
+ };
2987
+ function normalizeTranscript2(transcript, options) {
2988
+ const opts = { ...DEFAULT_OPTIONS3, ...options };
2989
+ const speakers = normalizeSpeakers(transcript.speakers ?? [], transcript, opts);
2990
+ const sentences = normalizeSentences(transcript.sentences ?? [], opts);
2991
+ const participants = normalizeParticipants(transcript, opts);
2992
+ const summary = opts.includeSummary ? normalizeSummary(transcript.summary) : void 0;
2993
+ const attendees = normalizeAttendees(transcript.meeting_attendance ?? []);
2994
+ const channels = normalizeChannels(transcript.channels ?? []);
2995
+ const analytics = normalizeAnalytics(transcript.analytics);
2996
+ return {
2997
+ id: `fireflies:${transcript.id}`,
2998
+ title: transcript.title,
2999
+ date: new Date(transcript.date),
3000
+ duration: transcript.duration * 60,
3001
+ // minutes → seconds
3002
+ url: transcript.transcript_url,
3003
+ speakers,
3004
+ sentences,
3005
+ participants,
3006
+ summary,
3007
+ attendees,
3008
+ channels,
3009
+ analytics,
3010
+ source: {
3011
+ provider: "fireflies",
3012
+ originalId: transcript.id,
3013
+ rawData: opts.includeRawData ? transcript : void 0
3014
+ }
3015
+ };
3016
+ }
3017
+ function createNormalizer(options) {
3018
+ return (transcript) => normalizeTranscript2(transcript, options);
3019
+ }
3020
+ function normalizeSpeakers(speakers, transcript, opts) {
3021
+ return speakers.map((speaker) => ({
3022
+ id: speaker.id,
3023
+ name: opts.resolveSpeakerName(speaker, transcript)
3024
+ }));
3025
+ }
3026
+ function normalizeSentences(sentences, opts) {
3027
+ const timeMultiplier = opts.timeUnit === "milliseconds" ? 1e3 : 1;
3028
+ return sentences.map((sentence) => {
3029
+ const normalized = {
3030
+ index: sentence.index,
3031
+ speakerId: sentence.speaker_id,
3032
+ speakerName: sentence.speaker_name,
3033
+ text: sentence.text,
3034
+ rawText: sentence.raw_text,
3035
+ startTime: parseTime(sentence.start_time) * timeMultiplier,
3036
+ endTime: parseTime(sentence.end_time) * timeMultiplier
3037
+ };
3038
+ if (opts.includeAIFilters && sentence.ai_filters) {
3039
+ const sentiment = mapSentiment(sentence.ai_filters.sentiment);
3040
+ if (sentiment) {
3041
+ normalized.sentiment = sentiment;
3042
+ }
3043
+ if (sentence.ai_filters.question) {
3044
+ normalized.isQuestion = true;
3045
+ }
3046
+ if (sentence.ai_filters.task) {
3047
+ normalized.isActionItem = true;
3048
+ }
3049
+ }
3050
+ return normalized;
3051
+ });
3052
+ }
3053
+ function parseTime(timeStr) {
3054
+ const parsed = Number.parseFloat(timeStr);
3055
+ return Number.isNaN(parsed) ? 0 : parsed;
3056
+ }
3057
+ function mapSentiment(sentiment) {
3058
+ if (!sentiment) return void 0;
3059
+ const lower = sentiment.toLowerCase();
3060
+ if (lower === "positive") return "positive";
3061
+ if (lower === "negative") return "negative";
3062
+ if (lower === "neutral") return "neutral";
3063
+ return void 0;
3064
+ }
3065
+ function normalizeParticipants(transcript, opts) {
3066
+ const participants = transcript.participants ?? [];
3067
+ const attendeeMap = /* @__PURE__ */ new Map();
3068
+ for (const attendee of transcript.meeting_attendees ?? []) {
3069
+ if (attendee.email && attendee.name) {
3070
+ attendeeMap.set(attendee.email.toLowerCase(), attendee.name);
3071
+ }
3072
+ }
3073
+ return participants.map((email) => {
3074
+ const isOrganizer = email.toLowerCase() === transcript.organizer_email.toLowerCase();
3075
+ const attendeeName = attendeeMap.get(email.toLowerCase());
3076
+ const enrichment = opts.enrichParticipant(email, transcript);
3077
+ return {
3078
+ name: enrichment.name ?? attendeeName ?? "",
3079
+ email,
3080
+ role: enrichment.role ?? (isOrganizer ? "organizer" : "attendee")
3081
+ };
3082
+ });
3083
+ }
3084
+ function normalizeSummary(summary) {
3085
+ if (!summary) return void 0;
3086
+ const keyPoints = parseKeyPoints(summary.shorthand_bullet);
3087
+ return {
3088
+ overview: summary.overview,
3089
+ keyPoints: keyPoints.length > 0 ? keyPoints : void 0,
3090
+ actionItems: summary.action_items,
3091
+ outline: summary.outline,
3092
+ topics: summary.topics_discussed
3093
+ };
3094
+ }
3095
+ function parseKeyPoints(shorthandBullet) {
3096
+ if (!shorthandBullet) return [];
3097
+ return shorthandBullet.split("\n").map((line) => line.replace(/^[-*•]\s*/, "").trim()).filter((line) => line.length > 0);
3098
+ }
3099
+ function normalizeAttendees(attendance) {
3100
+ return attendance.map((a) => ({
3101
+ name: a.name,
3102
+ joinTime: a.join_time ? new Date(a.join_time) : void 0,
3103
+ leaveTime: a.leave_time ? new Date(a.leave_time) : void 0
3104
+ }));
3105
+ }
3106
+ function normalizeChannels(channels) {
3107
+ return channels.map((ch) => ({
3108
+ id: ch.id,
3109
+ title: ch.title,
3110
+ isPrivate: ch.is_private ?? false
3111
+ }));
3112
+ }
3113
+ function normalizeAnalytics(analytics) {
3114
+ if (!analytics?.sentiments) return void 0;
3115
+ return {
3116
+ sentiments: {
3117
+ positive: analytics.sentiments.positive_pct ?? 0,
3118
+ neutral: analytics.sentiments.neutral_pct ?? 0,
3119
+ negative: analytics.sentiments.negative_pct ?? 0
3120
+ }
3121
+ };
3122
+ }
3123
+ function delay3(ms) {
3124
+ return new Promise((resolve) => setTimeout(resolve, ms));
3125
+ }
3126
+ async function* normalizeTranscripts(transcripts, options) {
3127
+ const { delayMs = 0, ...normalizationOptions } = options ?? {};
3128
+ let isFirst = true;
3129
+ for await (const transcript of transcripts) {
3130
+ if (!isFirst && delayMs > 0) {
3131
+ await delay3(delayMs);
3132
+ }
3133
+ isFirst = false;
3134
+ try {
3135
+ const result = normalizeTranscript2(transcript, normalizationOptions);
3136
+ yield { item: transcript, result };
3137
+ } catch (err) {
3138
+ yield {
3139
+ item: transcript,
3140
+ error: err instanceof Error ? err : new Error(String(err))
3141
+ };
3142
+ }
3143
+ }
3144
+ }
3145
+ async function normalizeTranscriptsAll(transcripts, options) {
3146
+ const results = [];
3147
+ for await (const result of normalizeTranscripts(transcripts, options)) {
3148
+ results.push(result);
3149
+ }
3150
+ return results;
3151
+ }
3152
+
3153
+ // src/helpers/speaker-analytics.ts
3154
+ function analyzeSpeakers(transcript, options = {}) {
3155
+ const {
3156
+ mergeSpeakersByName = true,
3157
+ roundPercentages = true,
3158
+ unbalancedThreshold = 40,
3159
+ dominatedThreshold = 60
3160
+ } = options;
3161
+ const sentences = transcript.sentences ?? [];
3162
+ if (sentences.length === 0) {
3163
+ return emptyAnalytics();
3164
+ }
3165
+ const speakerMap = /* @__PURE__ */ new Map();
3166
+ let prevSpeakerKey = null;
3167
+ for (const sentence of sentences) {
3168
+ const groupKey = mergeSpeakersByName ? sentence.speaker_name : sentence.speaker_id;
3169
+ const data = getOrCreateSpeakerData(speakerMap, groupKey, sentence);
3170
+ data.sentences.push(sentence);
3171
+ data.talkTime += parseDuration(sentence);
3172
+ data.wordCount += countWords(sentence.text);
3173
+ if (groupKey !== prevSpeakerKey) {
3174
+ data.turnCount++;
3175
+ prevSpeakerKey = groupKey;
3176
+ }
3177
+ }
3178
+ const totalTalkTime = sumTalkTime(speakerMap);
3179
+ const totalDuration = calculateDuration2(sentences);
3180
+ const totalWords = sumWords(speakerMap);
3181
+ const speakers = buildSpeakerStats(speakerMap, totalTalkTime, roundPercentages);
3182
+ speakers.sort((a, b) => b.talkTime - a.talkTime);
3183
+ const dominant = speakers[0];
3184
+ return {
3185
+ speakers,
3186
+ totalDuration,
3187
+ totalTalkTime,
3188
+ totalSentences: sentences.length,
3189
+ totalWords,
3190
+ dominantSpeaker: dominant?.name ?? "",
3191
+ dominantSpeakerPercentage: dominant?.talkTimePercentage ?? 0,
3192
+ balance: classifyBalance(speakers, unbalancedThreshold, dominatedThreshold)
3193
+ };
3194
+ }
3195
+ function emptyAnalytics() {
3196
+ return {
3197
+ speakers: [],
3198
+ totalDuration: 0,
3199
+ totalTalkTime: 0,
3200
+ totalSentences: 0,
3201
+ totalWords: 0,
3202
+ dominantSpeaker: "",
3203
+ dominantSpeakerPercentage: 0,
3204
+ balance: "balanced"
3205
+ };
3206
+ }
3207
+ function getOrCreateSpeakerData(speakerMap, groupKey, sentence) {
3208
+ let data = speakerMap.get(groupKey);
3209
+ if (!data) {
3210
+ data = {
3211
+ id: sentence.speaker_id,
3212
+ // Use first encountered ID
3213
+ name: sentence.speaker_name,
3214
+ sentences: [],
3215
+ talkTime: 0,
3216
+ wordCount: 0,
3217
+ turnCount: 0
3218
+ };
3219
+ speakerMap.set(groupKey, data);
3220
+ }
3221
+ return data;
3222
+ }
3223
+ function parseDuration(sentence) {
3224
+ const start = Number.parseFloat(sentence.start_time);
3225
+ const end = Number.parseFloat(sentence.end_time);
3226
+ return Math.max(0, end - start);
3227
+ }
3228
+ function countWords(text) {
3229
+ if (!text || text.length === 0) return 0;
3230
+ return text.trim().split(/\s+/).filter((w) => w.length > 0).length;
3231
+ }
3232
+ function sumTalkTime(speakerMap) {
3233
+ let total = 0;
3234
+ for (const data of speakerMap.values()) {
3235
+ total += data.talkTime;
3236
+ }
3237
+ return total;
3238
+ }
3239
+ function sumWords(speakerMap) {
3240
+ let total = 0;
3241
+ for (const data of speakerMap.values()) {
3242
+ total += data.wordCount;
3243
+ }
3244
+ return total;
3245
+ }
3246
+ function calculateDuration2(sentences) {
3247
+ if (sentences.length === 0) return 0;
3248
+ const lastSentence = sentences[sentences.length - 1];
3249
+ return Number.parseFloat(lastSentence?.end_time ?? "0");
3250
+ }
3251
+ function buildSpeakerStats(speakerMap, totalTalkTime, roundPercentages) {
3252
+ const speakers = [];
3253
+ for (const data of speakerMap.values()) {
3254
+ const percentage = totalTalkTime > 0 ? data.talkTime / totalTalkTime * 100 : 0;
3255
+ const sentenceCount = data.sentences.length;
3256
+ const talkTimeMinutes = data.talkTime / 60;
3257
+ const wordsPerMinute = talkTimeMinutes > 0 ? data.wordCount / talkTimeMinutes : 0;
3258
+ const averageSentenceLength = sentenceCount > 0 ? data.wordCount / sentenceCount : 0;
3259
+ speakers.push({
3260
+ name: data.name,
3261
+ id: data.id,
3262
+ talkTime: data.talkTime,
3263
+ talkTimePercentage: roundPercentages ? Math.round(percentage) : percentage,
3264
+ sentenceCount,
3265
+ wordCount: data.wordCount,
3266
+ wordsPerMinute: roundPercentages ? Math.round(wordsPerMinute) : wordsPerMinute,
3267
+ averageSentenceLength,
3268
+ turnCount: data.turnCount
3269
+ });
3270
+ }
3271
+ return speakers;
3272
+ }
3273
+ function classifyBalance(speakers, unbalancedThreshold, dominatedThreshold) {
3274
+ if (speakers.length <= 2) return "balanced";
3275
+ const top = speakers[0]?.talkTimePercentage ?? 0;
3276
+ if (top > dominatedThreshold) return "dominated";
3277
+ if (top > unbalancedThreshold) return "unbalanced";
3278
+ return "balanced";
3279
+ }
3280
+
3281
+ // src/helpers/videos.ts
3282
+ async function* getMeetingVideos(client, options) {
3283
+ for await (const transcript of client.transcripts.listAll(options)) {
3284
+ if (transcript.video_url) {
3285
+ yield {
3286
+ transcript,
3287
+ videoUrl: transcript.video_url
3288
+ };
3289
+ }
3290
+ }
3291
+ }
3292
+ function hasVideo(transcript) {
3293
+ return typeof transcript.video_url === "string" && transcript.video_url.length > 0;
3294
+ }
3295
+ function verifyWebhookSignature(options) {
3296
+ const { payload, signature, secret } = options;
3297
+ if (!signature || !secret) {
3298
+ return false;
3299
+ }
3300
+ const payloadString = typeof payload === "string" ? payload : JSON.stringify(payload);
3301
+ const computed = createHmac("sha256", secret).update(payloadString).digest("hex");
3302
+ try {
3303
+ return timingSafeEqual(Buffer.from(signature), Buffer.from(computed));
3304
+ } catch {
3305
+ return false;
3306
+ }
3307
+ }
3308
+
3309
+ // src/webhooks/parse.ts
3310
+ var VALID_EVENT_TYPES = ["Transcription completed"];
3311
+ function isValidEventType(value) {
3312
+ return VALID_EVENT_TYPES.includes(value);
3313
+ }
3314
+ function isValidWebhookPayload(payload) {
3315
+ if (!payload || typeof payload !== "object") {
3316
+ return false;
3317
+ }
3318
+ const meetingId = payload["meetingId"];
3319
+ const eventType = payload["eventType"];
3320
+ const clientReferenceId = payload["clientReferenceId"];
3321
+ return typeof meetingId === "string" && typeof eventType === "string" && isValidEventType(eventType) && (clientReferenceId === void 0 || typeof clientReferenceId === "string");
3322
+ }
3323
+ function parseWebhookPayload(payload, options) {
3324
+ if (options?.signature && options?.secret) {
3325
+ const isValid = verifyWebhookSignature({
3326
+ payload,
3327
+ signature: options.signature,
3328
+ secret: options.secret
3329
+ });
3330
+ if (!isValid) {
3331
+ throw new WebhookVerificationError("Invalid webhook signature");
3332
+ }
3333
+ }
3334
+ if (!isValidWebhookPayload(payload)) {
3335
+ throw new WebhookParseError(
3336
+ "Invalid webhook payload: expected meetingId (string), eventType (valid event type), and optional clientReferenceId (string)"
3337
+ );
3338
+ }
3339
+ return payload;
3340
+ }
3341
+
3342
+ export { AuthenticationError, ChunkTimeoutError, ConnectionError, Deduplicator, FirefliesClient, FirefliesError, GraphQLError, NetworkError, NotFoundError, RateLimitError, RealtimeError, RealtimeStream, StreamClosedError, TimeoutError, TranscriptAccumulator, ValidationError, WebhookParseError, WebhookVerificationError, aggregateActionItems, analyzeMeetings, analyzeSpeakers, batch, batchAll, chunksToMarkdown, collectAll, createNormalizer, extractActionItems, extractDomain, filterActionItems, findExternalParticipantQuestions, formatActionItemsMarkdown, getMeetingVideos, getMeetingsForMultipleUsers, hasExternalParticipants, hasVideo, isValidWebhookPayload, normalizeTranscript2 as normalizeTranscript, normalizeTranscripts, normalizeTranscriptsAll, paginate, parseWebhookPayload, searchTranscript, transcriptToMarkdown, verifyWebhookSignature };
3343
+ //# sourceMappingURL=index.js.map
3344
+ //# sourceMappingURL=index.js.map