@minded-ai/mindedjs 3.0.8-beta.12 → 3.1.9-beta.1

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 (56) hide show
  1. package/dist/cli/index.js +2 -9
  2. package/dist/cli/index.js.map +1 -1
  3. package/dist/cli/runCommand.d.ts +1 -1
  4. package/dist/cli/runCommand.d.ts.map +1 -1
  5. package/dist/cli/runCommand.js +31 -23
  6. package/dist/cli/runCommand.js.map +1 -1
  7. package/dist/index.d.ts +2 -1
  8. package/dist/index.d.ts.map +1 -1
  9. package/dist/index.js +6 -3
  10. package/dist/index.js.map +1 -1
  11. package/dist/internalTools/documentExtraction/documentExtraction.d.ts +112 -102
  12. package/dist/internalTools/documentExtraction/documentExtraction.d.ts.map +1 -1
  13. package/dist/internalTools/documentExtraction/documentExtraction.js +146 -705
  14. package/dist/internalTools/documentExtraction/documentExtraction.js.map +1 -1
  15. package/dist/internalTools/documentExtraction/extractStructuredData.d.ts +57 -0
  16. package/dist/internalTools/documentExtraction/extractStructuredData.d.ts.map +1 -0
  17. package/dist/internalTools/documentExtraction/extractStructuredData.js +121 -0
  18. package/dist/internalTools/documentExtraction/extractStructuredData.js.map +1 -0
  19. package/dist/internalTools/documentExtraction/parseDocumentLocal.d.ts +16 -0
  20. package/dist/internalTools/documentExtraction/parseDocumentLocal.d.ts.map +1 -0
  21. package/dist/internalTools/documentExtraction/parseDocumentLocal.js +547 -0
  22. package/dist/internalTools/documentExtraction/parseDocumentLocal.js.map +1 -0
  23. package/dist/internalTools/documentExtraction/parseDocumentManaged.d.ts +13 -0
  24. package/dist/internalTools/documentExtraction/parseDocumentManaged.d.ts.map +1 -0
  25. package/dist/internalTools/documentExtraction/parseDocumentManaged.js +150 -0
  26. package/dist/internalTools/documentExtraction/parseDocumentManaged.js.map +1 -0
  27. package/dist/nodes/addAppToolNode.d.ts.map +1 -1
  28. package/dist/nodes/addAppToolNode.js +20 -1
  29. package/dist/nodes/addAppToolNode.js.map +1 -1
  30. package/dist/toolsLibrary/classifier.d.ts +2 -2
  31. package/dist/toolsLibrary/parseDocument.d.ts +11 -10
  32. package/dist/toolsLibrary/parseDocument.d.ts.map +1 -1
  33. package/dist/toolsLibrary/parseDocument.js +33 -189
  34. package/dist/toolsLibrary/parseDocument.js.map +1 -1
  35. package/dist/toolsLibrary/withBrowserSession.d.ts.map +1 -1
  36. package/dist/toolsLibrary/withBrowserSession.js +70 -2
  37. package/dist/toolsLibrary/withBrowserSession.js.map +1 -1
  38. package/dist/types/Flows.types.d.ts +1 -0
  39. package/dist/types/Flows.types.d.ts.map +1 -1
  40. package/dist/types/Flows.types.js.map +1 -1
  41. package/dist/utils/schemaUtils.js +1 -1
  42. package/dist/utils/schemaUtils.js.map +1 -1
  43. package/docs/tooling/document-processing.md +235 -174
  44. package/package.json +2 -1
  45. package/src/cli/index.ts +2 -10
  46. package/src/cli/runCommand.ts +31 -25
  47. package/src/index.ts +2 -1
  48. package/src/internalTools/documentExtraction/documentExtraction.ts +184 -767
  49. package/src/internalTools/documentExtraction/extractStructuredData.ts +140 -0
  50. package/src/internalTools/documentExtraction/parseDocumentLocal.ts +660 -0
  51. package/src/internalTools/documentExtraction/parseDocumentManaged.ts +152 -0
  52. package/src/nodes/addAppToolNode.ts +30 -7
  53. package/src/toolsLibrary/parseDocument.ts +38 -206
  54. package/src/toolsLibrary/withBrowserSession.ts +89 -4
  55. package/src/types/Flows.types.ts +1 -0
  56. package/src/utils/schemaUtils.ts +1 -1
@@ -0,0 +1,660 @@
1
+ import os from 'os';
2
+ import path from 'path';
3
+ import fsp from 'fs/promises';
4
+ import { logger } from '../../utils/logger';
5
+
6
+ export async function parseDocumentWithLocalService({
7
+ documentSource,
8
+ isDocumentUrl,
9
+ sessionId,
10
+ llamaCloudApiKey,
11
+ useBase64,
12
+ }: {
13
+ isDocumentUrl: boolean;
14
+ documentSource: string;
15
+ sessionId: string;
16
+ llamaCloudApiKey?: string;
17
+ useBase64?: boolean;
18
+ }) {
19
+ logger.info({
20
+ msg: '[DocumentParser] Parsing document locally',
21
+ sessionId,
22
+ documentSource,
23
+ sourceType: isDocumentUrl ? 'url' : 'path',
24
+ });
25
+
26
+ const startTime = Date.now();
27
+
28
+ try {
29
+ // Determine document source and content
30
+ const { content, fileType, fileSize } = await getDocumentContent({ documentSource, isDocumentUrl, sessionId });
31
+
32
+ // Process document content based on type
33
+ let processedContent: string;
34
+
35
+ if (isImageFile(fileType)) {
36
+ processedContent = await processImageDocument({
37
+ content,
38
+ llamaCloudApiKey,
39
+ fileType,
40
+ filePath: isDocumentUrl ? undefined : documentSource,
41
+ useBase64,
42
+ sessionId,
43
+ });
44
+ } else {
45
+ processedContent = await processTextDocument({
46
+ content,
47
+ llamaCloudApiKey,
48
+ fileType,
49
+ filePath: isDocumentUrl ? undefined : documentSource,
50
+ sessionId,
51
+ });
52
+ }
53
+
54
+ logger.info({
55
+ msg: '[DocumentParser] Document content processed',
56
+ sessionId,
57
+ fileType,
58
+ contentLength: processedContent.length,
59
+ });
60
+
61
+ const processingTime = Date.now() - startTime;
62
+
63
+ return {
64
+ rawContent: processedContent,
65
+ metadata: {
66
+ fileSize,
67
+ fileType,
68
+ processingTime,
69
+ contentLength: processedContent.length,
70
+ },
71
+ };
72
+ } catch (err) {
73
+ logger.error({
74
+ message: '[DocumentParser] Document processing failed',
75
+ sessionId,
76
+ err,
77
+ });
78
+ throw new Error(`Document processing failed: ${err instanceof Error ? err.message : String(err)}`);
79
+ }
80
+ }
81
+
82
+ async function getDocumentContent({
83
+ documentSource,
84
+ isDocumentUrl,
85
+ sessionId,
86
+ }: {
87
+ isDocumentUrl: boolean;
88
+ documentSource: string;
89
+ sessionId: string;
90
+ }): Promise<{
91
+ content: Buffer;
92
+ fileType: string;
93
+ fileSize?: number;
94
+ }> {
95
+ // Load the document from URL
96
+ if (isDocumentUrl) {
97
+ return fetchDocumentFromUrl({ documentSource, sessionId });
98
+ }
99
+ return loadDocumentFromFile({ documentSource, sessionId });
100
+ }
101
+
102
+ async function fetchDocumentFromUrl({ documentSource, sessionId }: { documentSource: string; sessionId: string }): Promise<{
103
+ content: Buffer;
104
+ fileType: string;
105
+ fileSize?: number;
106
+ }> {
107
+ logger.debug({
108
+ msg: '[DocumentParser] Fetching document from URL',
109
+ sessionId,
110
+ documentSource,
111
+ });
112
+
113
+ const response = await fetch(documentSource);
114
+
115
+ logger.debug({
116
+ msg: '[DocumentParser] Document fetched from URL',
117
+ sessionId,
118
+ documentSource,
119
+ status: response.status,
120
+ ok: response.ok,
121
+ });
122
+
123
+ if (!response.ok) {
124
+ throw new Error(`Failed to fetch document from URL: ${response.statusText}`);
125
+ }
126
+
127
+ const arrayBuffer = await response.arrayBuffer();
128
+ const content = Buffer.from(arrayBuffer);
129
+ const fileType = inferFileTypeFromUrl(documentSource) || inferFileTypeFromBuffer(content);
130
+
131
+ logger.debug({
132
+ msg: '[DocumentParser] Successfully fetched document from URL',
133
+ sessionId,
134
+ documentSource,
135
+ contentSize: content.length,
136
+ fileType,
137
+ });
138
+
139
+ return {
140
+ content,
141
+ fileType,
142
+ fileSize: content.length,
143
+ };
144
+ }
145
+
146
+ async function loadDocumentFromFile({ documentSource, sessionId }: { documentSource: string; sessionId: string }): Promise<{
147
+ content: Buffer;
148
+ fileType: string;
149
+ fileSize?: number;
150
+ }> {
151
+ logger.debug({
152
+ msg: '[DocumentParser] Loading document from file',
153
+ sessionId,
154
+ documentSource,
155
+ });
156
+
157
+ // Check that the document file exists
158
+ try {
159
+ await fsp.access(documentSource)
160
+ } catch {
161
+ throw new Error(`Document not found: ${documentSource}`);
162
+ }
163
+
164
+ const content = await fsp.readFile(documentSource);
165
+ const fileType = path.extname(documentSource).toLowerCase();
166
+
167
+ logger.debug({
168
+ msg: '[DocumentParser] Document loaded from file',
169
+ sessionId,
170
+ documentSource,
171
+ contentSize: content.length,
172
+ fileType,
173
+ });
174
+
175
+ return {
176
+ content,
177
+ fileType,
178
+ fileSize: content.length,
179
+ };
180
+ }
181
+
182
+ /**
183
+ * Process image documents by converting them to a standardized format
184
+ */
185
+ async function processImageDocument({
186
+ content,
187
+ llamaCloudApiKey,
188
+ filePath,
189
+ fileType,
190
+ useBase64,
191
+ sessionId,
192
+ }: {
193
+ content: Buffer;
194
+ llamaCloudApiKey?: string;
195
+ filePath?: string;
196
+ fileType: string;
197
+ useBase64?: boolean;
198
+ sessionId: string;
199
+ }): Promise<string> {
200
+ try {
201
+ // First, try to use LlamaParser if available for text extraction
202
+ if (filePath && llamaCloudApiKey) {
203
+ logger.debug({
204
+ msg: '[DocumentParser] Calling parseWithLlamaCloud for image',
205
+ sessionId,
206
+ filePath,
207
+ });
208
+ const parsedContent = await parseWithLlamaCloud({ filePath, llamaCloudApiKey, sessionId });
209
+ logger.debug({
210
+ msg: '[DocumentParser] parseWithLlamaCloud returned for image',
211
+ sessionId,
212
+ hasContent: !!parsedContent,
213
+ contentLength: parsedContent?.length,
214
+ });
215
+ if (parsedContent) {
216
+ return parsedContent;
217
+ }
218
+ }
219
+
220
+ // If no file path, create a temporary file for LlamaCloud parsing
221
+ if (!filePath && llamaCloudApiKey) {
222
+ const tempDir = os.tmpdir();
223
+ const tempFileName = `temp_${Date.now()}${fileType}`;
224
+ const tempFilePath = path.join(tempDir, tempFileName);
225
+
226
+ logger.debug({
227
+ msg: '[DocumentParser] Creating temp file for image',
228
+ sessionId,
229
+ tempFilePath,
230
+ contentSize: content.length,
231
+ });
232
+
233
+ try {
234
+ await fsp.writeFile(tempFilePath, content);
235
+ logger.debug({
236
+ msg: '[DocumentParser] Calling parseWithLlamaCloud for temp image',
237
+ sessionId,
238
+ tempFilePath,
239
+ });
240
+ const parsedContent = await parseWithLlamaCloud({ filePath: tempFilePath, llamaCloudApiKey, sessionId });
241
+ logger.debug({
242
+ msg: '[DocumentParser] parseWithLlamaCloud returned for temp image',
243
+ sessionId,
244
+ hasContent: !!parsedContent,
245
+ contentLength: parsedContent?.length,
246
+ });
247
+ await fsp.unlink(tempFilePath);
248
+
249
+ if (parsedContent) {
250
+ return parsedContent;
251
+ }
252
+ } catch (err) {
253
+ // Clean up temp file on error
254
+ try {
255
+ await fsp.access(tempFilePath);
256
+ await fsp.unlink(tempFilePath);
257
+ } catch {
258
+ // pass
259
+ }
260
+ logger.warn({
261
+ msg: '[DocumentParser] Failed to parse image with LlamaCloud',
262
+ sessionId,
263
+ err,
264
+ });
265
+ }
266
+ }
267
+
268
+ logger.warn({
269
+ msg: '[DocumentParser] Sharp module not available. Using original image without optimization.',
270
+ sessionId,
271
+ fileType,
272
+ contentSize: content.length,
273
+ });
274
+
275
+ // If sharp is not available, use the original image
276
+ if (useBase64) {
277
+ // Return original image as base64
278
+ const base64Image = content.toString('base64');
279
+ const mimeType = getMimeType(fileType);
280
+ return `data:${mimeType};base64,${base64Image}`;
281
+ } else {
282
+ // Without sharp and without base64, we cannot process the image
283
+ return `[IMAGE CONTENT - ${fileType.toUpperCase()} file. Size: ${
284
+ content.length
285
+ } bytes. Consider using LLAMA_CLOUD_API_KEY for text extraction or set useBase64: true]`;
286
+ }
287
+ } catch (err) {
288
+ throw new Error(`Failed to process image document: ${err instanceof Error ? err.message : String(err)}`);
289
+ }
290
+ }
291
+
292
+ /**
293
+ * Process text-based documents using LlamaParser or fallback methods
294
+ */
295
+ async function processTextDocument({
296
+ content,
297
+ llamaCloudApiKey,
298
+ filePath,
299
+ fileType,
300
+ sessionId,
301
+ }: {
302
+ content: Buffer | string;
303
+ llamaCloudApiKey?: string;
304
+ filePath?: string;
305
+ fileType?: string;
306
+ sessionId: string;
307
+ }): Promise<string> {
308
+ // Try LlamaCloud parsing if we have a file path
309
+ if (filePath && llamaCloudApiKey) {
310
+ const parsedContent = await parseWithLlamaCloud({ filePath, llamaCloudApiKey, sessionId });
311
+ if (parsedContent) {
312
+ return parsedContent;
313
+ }
314
+ }
315
+
316
+ // If no file path but we have content and LlamaCloud API key, create a temp file
317
+ if (!filePath && llamaCloudApiKey && Buffer.isBuffer(content)) {
318
+ const tempDir = os.tmpdir();
319
+ const tempFileName = `temp_${Date.now()}${fileType || '.txt'}`;
320
+ const tempFilePath = path.join(tempDir, tempFileName);
321
+
322
+ try {
323
+ await fsp.writeFile(tempFilePath, content);
324
+ const parsedContent = await parseWithLlamaCloud({ filePath: tempFilePath, llamaCloudApiKey, sessionId });
325
+ await fsp.unlink(tempFilePath);
326
+
327
+ if (parsedContent) {
328
+ return parsedContent;
329
+ }
330
+ } catch (err) {
331
+ // Clean up temp file on error
332
+ try {
333
+ await fsp.access(tempFilePath);
334
+ await fsp.unlink(tempFilePath);
335
+ } catch {
336
+ // pass
337
+ }
338
+ logger.warn({
339
+ msg: '[DocumentParser] Failed to parse text document with LlamaCloud',
340
+ sessionId,
341
+ err,
342
+ });
343
+ }
344
+ }
345
+
346
+ // Fallback: handle based on a file type
347
+ if (typeof content === 'string') {
348
+ return content;
349
+ }
350
+
351
+ // Basic text extraction for simple formats
352
+ if (['.txt', '.md', '.html', '.htm', '.xml', '.csv'].includes(fileType || '')) {
353
+ return content.toString('utf-8');
354
+ }
355
+
356
+ // For unsupported binary formats without LlamaParser
357
+ throw new Error(`Unsupported document type ${fileType}. Please provide LLAMA_CLOUD_API_KEY for advanced document processing.`);
358
+ }
359
+
360
+ /**
361
+ * Parse document using LlamaCloud REST API
362
+ */
363
+ async function parseWithLlamaCloud({
364
+ filePath,
365
+ llamaCloudApiKey,
366
+ sessionId,
367
+ }: {
368
+ filePath: string;
369
+ llamaCloudApiKey: string;
370
+ sessionId: string;
371
+ }): Promise<string | null> {
372
+ try {
373
+ // Step 1: Upload file and start parsing
374
+ const fileContent = await fsp.readFile(filePath);
375
+ const fileName = path.basename(filePath);
376
+ const mimeType = getMimeType(path.extname(filePath));
377
+
378
+ const formData = new FormData();
379
+ const blob = new Blob([new Uint8Array(fileContent)], { type: mimeType });
380
+ formData.append('file', blob, fileName);
381
+ formData.append('premium_mode', 'true');
382
+
383
+ const uploadResponse = await fetch('https://api.cloud.llamaindex.ai/api/v1/parsing/upload', {
384
+ method: 'POST',
385
+ headers: {
386
+ Accept: 'application/json',
387
+ Authorization: `Bearer ${llamaCloudApiKey}`,
388
+ },
389
+ body: formData,
390
+ });
391
+
392
+ if (!uploadResponse.ok) {
393
+ const errorText = await uploadResponse.text();
394
+ throw new Error(`Failed to upload file: ${uploadResponse.status} - ${errorText}`);
395
+ }
396
+
397
+ const uploadResult = await uploadResponse.json();
398
+ const jobId = uploadResult.id || uploadResult.job_id;
399
+
400
+ if (!jobId) {
401
+ throw new Error('No job ID returned from upload');
402
+ }
403
+
404
+ logger.info({
405
+ msg: '[DocumentParser] File uploaded to LlamaCloud',
406
+ sessionId,
407
+ jobId,
408
+ fileName,
409
+ });
410
+
411
+ // Step 2: Poll for job completion
412
+ let attempts = 0;
413
+ const maxAttempts = 60; // 60 attempts with 2 second delay = 2 minutes max
414
+ const pollDelay = 2000; // 2 seconds
415
+
416
+ while (attempts < maxAttempts) {
417
+ const statusResponse = await fetch(`https://api.cloud.llamaindex.ai/api/v1/parsing/job/${jobId}`, {
418
+ method: 'GET',
419
+ headers: {
420
+ Accept: 'application/json',
421
+ Authorization: `Bearer ${llamaCloudApiKey}`,
422
+ },
423
+ });
424
+
425
+ if (!statusResponse.ok) {
426
+ throw new Error(`Failed to check job status: ${statusResponse.status}`);
427
+ }
428
+
429
+ const statusResult = await statusResponse.json();
430
+ const status = statusResult.status || statusResult.job_status;
431
+
432
+ if (status === 'SUCCESS' || status === 'COMPLETED' || status === 'completed') {
433
+ // Step 3: Retrieve results in Markdown
434
+
435
+ // Create an AbortController for timeout
436
+ const controller = new AbortController();
437
+ const timeout = setTimeout(() => controller.abort(), 20000); // 20 second timeout
438
+
439
+ let resultResponse;
440
+ try {
441
+ resultResponse = await fetch(`https://api.cloud.llamaindex.ai/api/v1/parsing/job/${jobId}/result/markdown`, {
442
+ method: 'GET',
443
+ headers: {
444
+ Accept: 'application/json',
445
+ Authorization: `Bearer ${llamaCloudApiKey}`,
446
+ },
447
+ signal: controller.signal,
448
+ });
449
+ } catch (fetchError) {
450
+ clearTimeout(timeout);
451
+ if (fetchError instanceof Error && fetchError.name === 'AbortError') {
452
+ throw new Error('Timeout fetching results from LlamaCloud after 20 seconds');
453
+ }
454
+ throw fetchError;
455
+ }
456
+
457
+ clearTimeout(timeout);
458
+
459
+ if (!resultResponse.ok) {
460
+ const errorText = await resultResponse.text();
461
+ throw new Error(`Failed to retrieve results: ${resultResponse.status} - ${errorText}`);
462
+ }
463
+
464
+ let resultData: any;
465
+ try {
466
+ // Read response using manual stream reading (more reliable than text())
467
+ let responseText;
468
+ if (resultResponse.body) {
469
+ const reader = resultResponse.body.getReader();
470
+ const chunks: Uint8Array[] = [];
471
+ let totalLength = 0;
472
+
473
+ try {
474
+ while (true) {
475
+ const { done, value } = await reader.read();
476
+ if (done) break;
477
+ if (value) {
478
+ chunks.push(value);
479
+ totalLength += value.length;
480
+ }
481
+ }
482
+
483
+ // Combine chunks
484
+ const combined = new Uint8Array(totalLength);
485
+ let offset = 0;
486
+ for (const chunk of chunks) {
487
+ combined.set(chunk, offset);
488
+ offset += chunk.length;
489
+ }
490
+
491
+ responseText = new TextDecoder().decode(combined);
492
+ } finally {
493
+ reader.releaseLock();
494
+ }
495
+ } else {
496
+ responseText = await resultResponse.text();
497
+ }
498
+
499
+ // Try to parse as JSON, but if it fails, use the text directly
500
+ try {
501
+ resultData = JSON.parse(responseText);
502
+ } catch {
503
+ // If it's not JSON, assume it's the markdown content directly
504
+ resultData = responseText;
505
+ }
506
+ } catch (textError) {
507
+ logger.error({
508
+ msg: '[DocumentParser] Failed to read response text',
509
+ sessionId,
510
+ jobId,
511
+ error: textError instanceof Error ? textError.message : String(textError),
512
+ stack: textError instanceof Error ? textError.stack : undefined,
513
+ });
514
+ throw new Error('Failed to read response from LlamaCloud');
515
+ }
516
+
517
+ logger.debug({
518
+ msg: '[DocumentParser] Result data structure',
519
+ sessionId,
520
+ jobId,
521
+ dataType: typeof resultData,
522
+ keys: typeof resultData === 'object' && resultData !== null ? Object.keys(resultData) : [],
523
+ hasMarkdown: typeof resultData === 'object' && 'markdown' in resultData,
524
+ hasContent: typeof resultData === 'object' && 'content' in resultData,
525
+ hasText: typeof resultData === 'object' && 'text' in resultData,
526
+ });
527
+
528
+ // The API might return the markdown directly as a string or nested in an object
529
+ let markdownContent: string;
530
+ if (typeof resultData === 'string') {
531
+ markdownContent = resultData;
532
+ } else {
533
+ markdownContent = resultData.markdown || resultData.content || resultData.text || '';
534
+ }
535
+
536
+ if (!markdownContent) {
537
+ logger.error({
538
+ msg: '[DocumentParser] No content in result',
539
+ sessionId,
540
+ jobId,
541
+ resultData: JSON.stringify(resultData).substring(0, 500),
542
+ });
543
+ throw new Error('No content returned from parsing');
544
+ }
545
+
546
+ logger.info({
547
+ msg: '[DocumentParser] Successfully parsed document with LlamaCloud',
548
+ sessionId,
549
+ jobId,
550
+ contentLength: markdownContent.length,
551
+ preview: markdownContent.substring(0, 100),
552
+ });
553
+
554
+ logger.debug({
555
+ msg: '[DocumentParser] About to return markdown content',
556
+ sessionId,
557
+ jobId,
558
+ });
559
+
560
+ return markdownContent;
561
+ } else if (status === 'FAILED' || status === 'ERROR' || status === 'failed') {
562
+ throw new Error(`Parsing job failed: ${statusResult.error || 'Unknown error'}`);
563
+ }
564
+
565
+ // Wait before next attempt
566
+ await new Promise((resolve) => setTimeout(resolve, pollDelay));
567
+ attempts++;
568
+ }
569
+
570
+ throw new Error('Parsing job timed out after 2 minutes');
571
+ } catch (err) {
572
+ logger.warn({
573
+ message: '[DocumentParser] LlamaCloud parsing failed',
574
+ sessionId,
575
+ err,
576
+ });
577
+ return null;
578
+ } finally {
579
+ logger.debug({
580
+ msg: '[DocumentParser] parseWithLlamaCloud finished',
581
+ sessionId,
582
+ filePath,
583
+ });
584
+ }
585
+ }
586
+
587
+ /**
588
+ * Infer file type from buffer content
589
+ */
590
+ function inferFileTypeFromBuffer(buffer: Buffer): string {
591
+ // Check common file signatures
592
+ const signatures: { [key: string]: string } = {
593
+ '89504E47': '.png',
594
+ FFD8FF: '.jpg',
595
+ '47494638': '.gif',
596
+ '25504446': '.pdf',
597
+ '504B0304': '.zip', // Also used by docx, xlsx, pptx
598
+ D0CF11E0: '.doc', // Also xls, ppt
599
+ };
600
+
601
+ const hex = buffer.toString('hex', 0, 4).toUpperCase();
602
+
603
+ for (const [signature, type] of Object.entries(signatures)) {
604
+ if (hex.startsWith(signature)) {
605
+ return type;
606
+ }
607
+ }
608
+
609
+ return '.unknown';
610
+ }
611
+
612
+ /**
613
+ * Get MIME type for file extension
614
+ */
615
+ function getMimeType(fileExtension: string): string {
616
+ const mimeTypes: { [key: string]: string } = {
617
+ '.pdf': 'application/pdf',
618
+ '.doc': 'application/msword',
619
+ '.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
620
+ '.txt': 'text/plain',
621
+ '.rtf': 'application/rtf',
622
+ '.jpg': 'image/jpeg',
623
+ '.jpeg': 'image/jpeg',
624
+ '.png': 'image/png',
625
+ '.gif': 'image/gif',
626
+ '.bmp': 'image/bmp',
627
+ '.webp': 'image/webp',
628
+ '.tiff': 'image/tiff',
629
+ '.xls': 'application/vnd.ms-excel',
630
+ '.xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
631
+ '.csv': 'text/csv',
632
+ '.html': 'text/html',
633
+ '.htm': 'text/html',
634
+ '.xml': 'application/xml',
635
+ '.md': 'text/markdown',
636
+ };
637
+
638
+ return mimeTypes[fileExtension.toLowerCase()] || 'application/octet-stream';
639
+ }
640
+
641
+ /**
642
+ * Infer file type from URL
643
+ */
644
+ function inferFileTypeFromUrl(url: string): string | null {
645
+ try {
646
+ const pathname = new URL(url).pathname;
647
+ const extension = path.extname(pathname).toLowerCase();
648
+ return extension || null;
649
+ } catch {
650
+ return null;
651
+ }
652
+ }
653
+
654
+ /**
655
+ * Check if file is an image type
656
+ */
657
+ function isImageFile(fileType: string): boolean {
658
+ const imageTypes = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp', '.tiff'];
659
+ return imageTypes.includes(fileType.toLowerCase());
660
+ }