od-temp 1.0.4 → 1.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1470 @@
1
+ #!/usr/bin/env node
2
+ const require_index_cli = require('./index.cli.cjs');
3
+
4
+ //#region src/document/OCRProcessor.ts
5
+ /**
6
+ * OCR processor with optional Tesseract.js support
7
+ * Requires peer dependency: tesseract.js
8
+ */
9
+ var OCRProcessor = class {
10
+ constructor() {
11
+ try {
12
+ this.tesseract = require("tesseract.js");
13
+ } catch {}
14
+ }
15
+ /**
16
+ * Extract text from image buffer using OCR
17
+ */
18
+ async recognizeText(buffer, options) {
19
+ if (!this.tesseract) throw new Error("[OCRProcessor] OCR support requires tesseract.js. Install with: npm install tesseract.js");
20
+ const startTime = performance.now();
21
+ try {
22
+ const language = Array.isArray(options?.language) ? options.language.join("+") : options?.language || "eng";
23
+ const worker = await this.tesseract.createWorker(language, options?.oem || 3);
24
+ if (options?.psm !== void 0) await worker.setParameters({ tessedit_pageseg_mode: options.psm });
25
+ const result = await worker.recognize(buffer);
26
+ await worker.terminate();
27
+ const endTime = performance.now();
28
+ const processingTime = Math.round((endTime - startTime) * 100) / 100;
29
+ return {
30
+ text: result.data.text || "",
31
+ confidence: result.data.confidence || 0,
32
+ processingTime
33
+ };
34
+ } catch (error) {
35
+ throw new Error(`[OCRProcessor] OCR recognition failed: ${error.message}`);
36
+ }
37
+ }
38
+ /**
39
+ * Check if OCR is available (tesseract.js installed)
40
+ */
41
+ isAvailable() {
42
+ return !!this.tesseract;
43
+ }
44
+ /**
45
+ * Create a scheduler for batch OCR processing
46
+ * More efficient for processing multiple images
47
+ */
48
+ async createScheduler(workerCount = 4) {
49
+ if (!this.tesseract) throw new Error("[OCRProcessor] OCR support requires tesseract.js. Install with: npm install tesseract.js");
50
+ if (this.scheduler) await this.scheduler.terminate();
51
+ this.scheduler = this.tesseract.createScheduler();
52
+ const workers = [];
53
+ for (let i = 0; i < workerCount; i++) {
54
+ const worker = await this.tesseract.createWorker("eng");
55
+ this.scheduler.addWorker(worker);
56
+ workers.push(worker);
57
+ }
58
+ return this.scheduler;
59
+ }
60
+ /**
61
+ * Batch process multiple images
62
+ */
63
+ async recognizeBatch(buffers, _options) {
64
+ if (!this.tesseract) throw new Error("[OCRProcessor] OCR support requires tesseract.js. Install with: npm install tesseract.js");
65
+ const scheduler = await this.createScheduler();
66
+ try {
67
+ const results = await Promise.all(buffers.map(async (buffer) => {
68
+ const startTime = performance.now();
69
+ const result = await scheduler.addJob("recognize", buffer);
70
+ const endTime = performance.now();
71
+ return {
72
+ text: result.data.text || "",
73
+ confidence: result.data.confidence || 0,
74
+ processingTime: Math.round((endTime - startTime) * 100) / 100
75
+ };
76
+ }));
77
+ await scheduler.terminate();
78
+ this.scheduler = void 0;
79
+ return results;
80
+ } catch (error) {
81
+ if (scheduler) {
82
+ await scheduler.terminate();
83
+ this.scheduler = void 0;
84
+ }
85
+ throw new Error(`[OCRProcessor] Batch OCR failed: ${error.message}`);
86
+ }
87
+ }
88
+ /**
89
+ * Terminate any running scheduler
90
+ */
91
+ async cleanup() {
92
+ if (this.scheduler) {
93
+ await this.scheduler.terminate();
94
+ this.scheduler = void 0;
95
+ }
96
+ }
97
+ };
98
+
99
+ //#endregion
100
+ //#region src/document/JsonProcessor.ts
101
+ /**
102
+ * Processor for JSON documents
103
+ */
104
+ var JsonProcessor = class {
105
+ constructor() {
106
+ this.defaultOptions = {
107
+ maxDepth: 100,
108
+ scanKeys: false,
109
+ alwaysRedact: [],
110
+ skipPaths: [],
111
+ piiIndicatorKeys: [
112
+ "email",
113
+ "e-mail",
114
+ "mail",
115
+ "phone",
116
+ "tel",
117
+ "telephone",
118
+ "mobile",
119
+ "ssn",
120
+ "social_security",
121
+ "address",
122
+ "street",
123
+ "city",
124
+ "zip",
125
+ "postal",
126
+ "name",
127
+ "firstname",
128
+ "lastname",
129
+ "fullname",
130
+ "password",
131
+ "pwd",
132
+ "secret",
133
+ "token",
134
+ "key",
135
+ "card",
136
+ "credit_card",
137
+ "creditcard",
138
+ "account",
139
+ "iban",
140
+ "swift",
141
+ "passport",
142
+ "license",
143
+ "licence"
144
+ ],
145
+ preserveStructure: true
146
+ };
147
+ }
148
+ /**
149
+ * Parse JSON from buffer or string
150
+ */
151
+ parse(input) {
152
+ try {
153
+ const text = typeof input === "string" ? input : input.toString("utf-8");
154
+ return JSON.parse(text);
155
+ } catch (error) {
156
+ throw new Error(`[JsonProcessor] Invalid JSON: ${error.message}`);
157
+ }
158
+ }
159
+ /**
160
+ * Detect PII in JSON data
161
+ */
162
+ async detect(data, detector, options) {
163
+ const opts = {
164
+ ...this.defaultOptions,
165
+ ...options
166
+ };
167
+ const pathsDetected = [];
168
+ const matchesByPath = {};
169
+ const allDetections = [];
170
+ const promises = [];
171
+ this.traverse(data, "", opts, (path, value, key) => {
172
+ promises.push((async () => {
173
+ if (this.shouldSkip(path, opts.skipPaths)) return;
174
+ if (this.shouldAlwaysRedact(path, opts.alwaysRedact)) {
175
+ const detection = {
176
+ type: "SENSITIVE_FIELD",
177
+ value: String(value),
178
+ placeholder: `[SENSITIVE_FIELD]`,
179
+ position: [0, String(value).length],
180
+ severity: "high",
181
+ confidence: 1
182
+ };
183
+ matchesByPath[path] = [detection];
184
+ pathsDetected.push(path);
185
+ allDetections.push(detection);
186
+ return;
187
+ }
188
+ if (opts.scanKeys && key) {
189
+ const keyResult = await detector.detect(key);
190
+ if (keyResult.detections.length > 0) {
191
+ const keyPath = `${path}.__key__`;
192
+ matchesByPath[keyPath] = keyResult.detections;
193
+ pathsDetected.push(keyPath);
194
+ allDetections.push(...keyResult.detections);
195
+ }
196
+ }
197
+ const valueStr = String(value);
198
+ const result = await detector.detect(valueStr);
199
+ if (result.detections.length > 0) {
200
+ const boostedDetections = this.boostConfidenceFromKey(result.detections, key, opts.piiIndicatorKeys);
201
+ matchesByPath[path] = boostedDetections;
202
+ pathsDetected.push(path);
203
+ allDetections.push(...boostedDetections);
204
+ }
205
+ })());
206
+ });
207
+ await Promise.all(promises);
208
+ const original = JSON.stringify(data);
209
+ const redacted = this.redact(data, {
210
+ original,
211
+ redacted: original,
212
+ detections: allDetections,
213
+ redactionMap: {},
214
+ stats: { piiCount: allDetections.length },
215
+ pathsDetected,
216
+ matchesByPath
217
+ }, opts);
218
+ const redactionMap = {};
219
+ allDetections.forEach((det) => {
220
+ redactionMap[det.placeholder] = det.value;
221
+ });
222
+ return {
223
+ original,
224
+ redacted: typeof redacted === "string" ? redacted : JSON.stringify(redacted),
225
+ detections: allDetections,
226
+ redactionMap,
227
+ stats: { piiCount: allDetections.length },
228
+ pathsDetected,
229
+ matchesByPath
230
+ };
231
+ }
232
+ /**
233
+ * Redact PII in JSON data
234
+ */
235
+ redact(data, detectionResult, options) {
236
+ if (!{
237
+ ...this.defaultOptions,
238
+ ...options
239
+ }.preserveStructure) return this.parse(this.redactText(JSON.stringify(data, null, 2), detectionResult));
240
+ return this.redactPreservingStructure(data, detectionResult.pathsDetected);
241
+ }
242
+ /**
243
+ * Redact specific paths in JSON while preserving structure
244
+ */
245
+ redactPreservingStructure(data, pathsToRedact) {
246
+ const pathSet = new Set(pathsToRedact);
247
+ const redactValue = (value, currentPath) => {
248
+ if (pathSet.has(currentPath)) {
249
+ if (typeof value === "string") return "[REDACTED]";
250
+ else if (typeof value === "number") return 0;
251
+ else if (typeof value === "boolean") return false;
252
+ else if (value === null) return null;
253
+ else if (Array.isArray(value)) return [];
254
+ else if (typeof value === "object") return {};
255
+ return "[REDACTED]";
256
+ }
257
+ if (Array.isArray(value)) return value.map((item, index) => redactValue(item, `${currentPath}[${index}]`));
258
+ if (value !== null && typeof value === "object") {
259
+ const result = {};
260
+ for (const [key, val] of Object.entries(value)) result[key] = redactValue(val, currentPath ? `${currentPath}.${key}` : key);
261
+ return result;
262
+ }
263
+ return value;
264
+ };
265
+ return redactValue(data, "");
266
+ }
267
+ /**
268
+ * Simple text-based redaction (fallback)
269
+ */
270
+ redactText(text, detectionResult) {
271
+ let redacted = text;
272
+ const sortedDetections = [...detectionResult.detections].sort((a, b) => b.position[0] - a.position[0]);
273
+ for (const detection of sortedDetections) {
274
+ const [start, end] = detection.position;
275
+ redacted = redacted.slice(0, start) + detection.placeholder + redacted.slice(end);
276
+ }
277
+ return redacted;
278
+ }
279
+ /**
280
+ * Traverse JSON structure and call callback for each value
281
+ */
282
+ traverse(obj, path, options, callback, depth = 0) {
283
+ if (depth > options.maxDepth) throw new Error(`[JsonProcessor] Maximum depth (${options.maxDepth}) exceeded`);
284
+ if (obj === null || obj === void 0) return;
285
+ if (Array.isArray(obj)) {
286
+ obj.forEach((item, index) => {
287
+ const itemPath = path ? `${path}[${index}]` : `[${index}]`;
288
+ if (this.isPrimitive(item)) callback(itemPath, item);
289
+ this.traverse(item, itemPath, options, callback, depth + 1);
290
+ });
291
+ return;
292
+ }
293
+ if (typeof obj === "object") {
294
+ for (const [key, value] of Object.entries(obj)) {
295
+ const valuePath = path ? `${path}.${key}` : key;
296
+ if (this.isPrimitive(value)) callback(valuePath, value, key);
297
+ this.traverse(value, valuePath, options, callback, depth + 1);
298
+ }
299
+ return;
300
+ }
301
+ if (this.isPrimitive(obj)) callback(path, obj);
302
+ }
303
+ /**
304
+ * Check if value is primitive (string, number, boolean)
305
+ */
306
+ isPrimitive(value) {
307
+ return typeof value === "string" || typeof value === "number" || typeof value === "boolean";
308
+ }
309
+ /**
310
+ * Check if path should be skipped
311
+ */
312
+ shouldSkip(path, skipPaths) {
313
+ return skipPaths.some((skipPath) => {
314
+ if (path === skipPath) return true;
315
+ return new RegExp("^" + skipPath.replace(/\*/g, "[^.]+") + "$").test(path);
316
+ });
317
+ }
318
+ /**
319
+ * Check if path should always be redacted
320
+ */
321
+ shouldAlwaysRedact(path, alwaysRedact) {
322
+ return alwaysRedact.some((redactPath) => {
323
+ if (path === redactPath) return true;
324
+ return new RegExp("^" + redactPath.replace(/\*/g, "[^.]+") + "$").test(path);
325
+ });
326
+ }
327
+ /**
328
+ * Boost confidence if key name indicates PII
329
+ */
330
+ boostConfidenceFromKey(detections, key, piiIndicatorKeys) {
331
+ if (!key) return detections;
332
+ const keyLower = key.toLowerCase();
333
+ if (!piiIndicatorKeys.some((indicator) => keyLower.includes(indicator.toLowerCase()))) return detections;
334
+ return detections.map((detection) => ({
335
+ ...detection,
336
+ confidence: Math.min(1, (detection.confidence || .5) * 1.2)
337
+ }));
338
+ }
339
+ /**
340
+ * Extract all text values from JSON for simple text-based detection
341
+ */
342
+ extractText(data, options) {
343
+ const opts = {
344
+ ...this.defaultOptions,
345
+ ...options
346
+ };
347
+ const textParts = [];
348
+ this.traverse(data, "", opts, (_path, value, key) => {
349
+ if (opts.scanKeys && key) textParts.push(key);
350
+ if (typeof value === "string") textParts.push(value);
351
+ });
352
+ return textParts.join(" ");
353
+ }
354
+ /**
355
+ * Validate JSON buffer/string
356
+ */
357
+ isValid(input) {
358
+ try {
359
+ this.parse(input);
360
+ return true;
361
+ } catch {
362
+ return false;
363
+ }
364
+ }
365
+ /**
366
+ * Get JSON Lines (JSONL) support - split by newlines and parse each line
367
+ */
368
+ parseJsonLines(input) {
369
+ return (typeof input === "string" ? input : input.toString("utf-8")).split("\n").filter((line) => line.trim().length > 0).map((line, index) => {
370
+ try {
371
+ return JSON.parse(line);
372
+ } catch (error) {
373
+ throw new Error(`[JsonProcessor] Invalid JSON at line ${index + 1}: ${error.message}`);
374
+ }
375
+ });
376
+ }
377
+ /**
378
+ * Detect PII in JSON Lines format
379
+ */
380
+ async detectJsonLines(input, detector, options) {
381
+ const documents = this.parseJsonLines(input);
382
+ return Promise.all(documents.map((doc) => this.detect(doc, detector, options)));
383
+ }
384
+ };
385
+
386
+ //#endregion
387
+ //#region src/document/CsvProcessor.ts
388
+ /**
389
+ * CSV processor for tabular data
390
+ */
391
+ var CsvProcessor = class {
392
+ constructor() {
393
+ this.defaultOptions = {
394
+ quote: "\"",
395
+ escape: "\"",
396
+ skipEmptyLines: true,
397
+ piiIndicatorNames: [
398
+ "email",
399
+ "e-mail",
400
+ "mail",
401
+ "email_address",
402
+ "phone",
403
+ "tel",
404
+ "telephone",
405
+ "mobile",
406
+ "phone_number",
407
+ "ssn",
408
+ "social_security",
409
+ "social_security_number",
410
+ "address",
411
+ "street",
412
+ "street_address",
413
+ "city",
414
+ "zip",
415
+ "zipcode",
416
+ "postal",
417
+ "postcode",
418
+ "name",
419
+ "firstname",
420
+ "first_name",
421
+ "lastname",
422
+ "last_name",
423
+ "fullname",
424
+ "full_name",
425
+ "password",
426
+ "pwd",
427
+ "secret",
428
+ "token",
429
+ "api_key",
430
+ "card",
431
+ "credit_card",
432
+ "creditcard",
433
+ "card_number",
434
+ "account",
435
+ "account_number",
436
+ "iban",
437
+ "swift",
438
+ "passport",
439
+ "passport_number",
440
+ "license",
441
+ "licence",
442
+ "driver_license",
443
+ "dob",
444
+ "date_of_birth",
445
+ "birth_date",
446
+ "birthdate"
447
+ ],
448
+ treatFirstRowAsHeader: true
449
+ };
450
+ }
451
+ /**
452
+ * Parse CSV from buffer or string
453
+ */
454
+ parse(input, options) {
455
+ const opts = {
456
+ ...this.defaultOptions,
457
+ ...options
458
+ };
459
+ const text = typeof input === "string" ? input : input.toString("utf-8");
460
+ const delimiter = opts.delimiter || this.detectDelimiter(text);
461
+ const lines = text.split(/\r?\n/);
462
+ const rows = [];
463
+ let rowIndex = 0;
464
+ for (let i = 0; i < lines.length; i++) {
465
+ const line = lines[i];
466
+ if (opts.skipEmptyLines && line.trim().length === 0) continue;
467
+ if (opts.maxRows !== void 0 && rowIndex >= opts.maxRows) break;
468
+ const values = this.parseRow(line, delimiter, opts.quote, opts.escape);
469
+ rows.push({
470
+ index: rowIndex,
471
+ values
472
+ });
473
+ rowIndex++;
474
+ }
475
+ return rows;
476
+ }
477
+ /**
478
+ * Detect PII in CSV data
479
+ */
480
+ async detect(input, detector, options) {
481
+ const opts = {
482
+ ...this.defaultOptions,
483
+ ...options
484
+ };
485
+ const rows = this.parse(input, options);
486
+ if (rows.length === 0) {
487
+ const original = typeof input === "string" ? input : input.toString("utf-8");
488
+ return {
489
+ original,
490
+ redacted: original,
491
+ detections: [],
492
+ redactionMap: {},
493
+ stats: { piiCount: 0 },
494
+ rowCount: 0,
495
+ columnCount: 0,
496
+ columnStats: {},
497
+ matchesByCell: []
498
+ };
499
+ }
500
+ const hasHeader = opts.hasHeader !== void 0 ? opts.hasHeader : this.detectHeader(rows);
501
+ const headers = hasHeader && rows.length > 0 ? rows[0].values : void 0;
502
+ const dataRows = hasHeader ? rows.slice(1) : rows;
503
+ const columnCount = rows[0].values.length;
504
+ const columnNameToIndex = /* @__PURE__ */ new Map();
505
+ if (headers) headers.forEach((header, index) => {
506
+ columnNameToIndex.set(header.toLowerCase().trim(), index);
507
+ });
508
+ const alwaysRedactCols = new Set(opts.alwaysRedactColumns || []);
509
+ if (opts.alwaysRedactColumnNames && headers) opts.alwaysRedactColumnNames.forEach((name) => {
510
+ const index = columnNameToIndex.get(name.toLowerCase().trim());
511
+ if (index !== void 0) alwaysRedactCols.add(index);
512
+ });
513
+ const skipCols = new Set(opts.skipColumns || []);
514
+ const columnStats = {};
515
+ const matchesByCell = [];
516
+ const allDetections = [];
517
+ for (let col = 0; col < columnCount; col++) columnStats[col] = {
518
+ columnIndex: col,
519
+ columnName: headers?.[col],
520
+ piiCount: 0,
521
+ piiPercentage: 0,
522
+ piiTypes: []
523
+ };
524
+ for (const row of dataRows) for (let col = 0; col < row.values.length; col++) {
525
+ if (skipCols.has(col)) continue;
526
+ const cellValue = row.values[col];
527
+ if (alwaysRedactCols.has(col)) {
528
+ const detection = {
529
+ type: "SENSITIVE_COLUMN",
530
+ value: cellValue,
531
+ placeholder: `[SENSITIVE_COLUMN_${col}]`,
532
+ position: [0, cellValue.length],
533
+ severity: "high",
534
+ confidence: 1
535
+ };
536
+ matchesByCell.push({
537
+ row: row.index,
538
+ column: col,
539
+ columnName: headers?.[col],
540
+ value: cellValue,
541
+ matches: [detection]
542
+ });
543
+ allDetections.push(detection);
544
+ columnStats[col].piiCount++;
545
+ continue;
546
+ }
547
+ const result = await detector.detect(cellValue);
548
+ if (result.detections.length > 0) {
549
+ const boostedDetections = this.boostConfidenceFromColumnName(result.detections, headers?.[col], opts.piiIndicatorNames || []);
550
+ matchesByCell.push({
551
+ row: row.index,
552
+ column: col,
553
+ columnName: headers?.[col],
554
+ value: cellValue,
555
+ matches: boostedDetections
556
+ });
557
+ allDetections.push(...boostedDetections);
558
+ columnStats[col].piiCount += boostedDetections.length;
559
+ const columnTypes = new Set(columnStats[col].piiTypes);
560
+ boostedDetections.forEach((d) => columnTypes.add(d.type));
561
+ columnStats[col].piiTypes = Array.from(columnTypes);
562
+ }
563
+ }
564
+ for (let col = 0; col < columnCount; col++) {
565
+ const rowsWithPii = matchesByCell.filter((m) => m.column === col).length;
566
+ columnStats[col].piiPercentage = dataRows.length > 0 ? rowsWithPii / dataRows.length * 100 : 0;
567
+ }
568
+ const original = typeof input === "string" ? input : input.toString("utf-8");
569
+ const redacted = this.redact(original, {
570
+ original,
571
+ redacted: original,
572
+ detections: allDetections,
573
+ redactionMap: {},
574
+ stats: { piiCount: allDetections.length },
575
+ rowCount: dataRows.length,
576
+ columnCount,
577
+ headers,
578
+ columnStats,
579
+ matchesByCell
580
+ }, opts);
581
+ const redactionMap = {};
582
+ allDetections.forEach((det) => {
583
+ redactionMap[det.placeholder] = det.value;
584
+ });
585
+ return {
586
+ original,
587
+ redacted,
588
+ detections: allDetections,
589
+ redactionMap,
590
+ stats: { piiCount: allDetections.length },
591
+ rowCount: dataRows.length,
592
+ columnCount,
593
+ headers: headers?.filter((h) => h !== void 0),
594
+ columnStats,
595
+ matchesByCell
596
+ };
597
+ }
598
+ /**
599
+ * Redact PII in CSV data
600
+ */
601
+ redact(input, detectionResult, options) {
602
+ const opts = {
603
+ ...this.defaultOptions,
604
+ ...options
605
+ };
606
+ const rows = this.parse(input, options);
607
+ if (rows.length === 0) return "";
608
+ const delimiter = opts.delimiter || this.detectDelimiter(typeof input === "string" ? input : input.toString("utf-8"));
609
+ const hasHeader = detectionResult.headers !== void 0;
610
+ const redactionMap = /* @__PURE__ */ new Map();
611
+ for (const cellMatch of detectionResult.matchesByCell) {
612
+ if (!redactionMap.has(cellMatch.row)) redactionMap.set(cellMatch.row, /* @__PURE__ */ new Map());
613
+ redactionMap.get(cellMatch.row).set(cellMatch.column, "[REDACTED]");
614
+ }
615
+ const outputRows = [];
616
+ for (let i = 0; i < rows.length; i++) {
617
+ const row = rows[i];
618
+ if (hasHeader && i === 0) outputRows.push(this.formatRow(row.values, delimiter, opts.quote));
619
+ else {
620
+ const rowIndex = hasHeader ? i - 1 : i;
621
+ const redactedValues = row.values.map((value, colIndex) => {
622
+ return redactionMap.get(rowIndex)?.get(colIndex) || value;
623
+ });
624
+ outputRows.push(this.formatRow(redactedValues, delimiter, opts.quote));
625
+ }
626
+ }
627
+ return outputRows.join("\n");
628
+ }
629
+ /**
630
+ * Parse a single CSV row
631
+ */
632
+ parseRow(line, delimiter, quote, _escape) {
633
+ const values = [];
634
+ let current = "";
635
+ let inQuotes = false;
636
+ let i = 0;
637
+ while (i < line.length) {
638
+ const char = line[i];
639
+ const nextChar = line[i + 1];
640
+ if (char === quote) if (inQuotes && nextChar === quote) {
641
+ current += quote;
642
+ i += 2;
643
+ } else {
644
+ inQuotes = !inQuotes;
645
+ i++;
646
+ }
647
+ else if (char === delimiter && !inQuotes) {
648
+ values.push(current);
649
+ current = "";
650
+ i++;
651
+ } else {
652
+ current += char;
653
+ i++;
654
+ }
655
+ }
656
+ values.push(current);
657
+ return values;
658
+ }
659
+ /**
660
+ * Format a row as CSV
661
+ */
662
+ formatRow(values, delimiter, quote) {
663
+ return values.map((value) => {
664
+ if (value.includes(delimiter) || value.includes(quote) || value.includes("\n")) return `${quote}${value.replace(new RegExp(quote, "g"), quote + quote)}${quote}`;
665
+ return value;
666
+ }).join(delimiter);
667
+ }
668
+ /**
669
+ * Auto-detect CSV delimiter
670
+ */
671
+ detectDelimiter(text) {
672
+ const delimiters = [
673
+ ",",
674
+ " ",
675
+ ";",
676
+ "|"
677
+ ];
678
+ const lines = text.split(/\r?\n/).slice(0, 5);
679
+ let bestDelimiter = ",";
680
+ let bestScore = 0;
681
+ for (const delimiter of delimiters) {
682
+ const counts = lines.map((line) => {
683
+ let count = 0;
684
+ let inQuotes = false;
685
+ for (const char of line) {
686
+ if (char === "\"") inQuotes = !inQuotes;
687
+ if (char === delimiter && !inQuotes) count++;
688
+ }
689
+ return count;
690
+ });
691
+ if (counts.length > 0 && counts[0] > 0) {
692
+ const avg = counts.reduce((a, b) => a + b, 0) / counts.length;
693
+ const score = avg / (counts.reduce((sum, c) => sum + Math.pow(c - avg, 2), 0) / counts.length + 1);
694
+ if (score > bestScore) {
695
+ bestScore = score;
696
+ bestDelimiter = delimiter;
697
+ }
698
+ }
699
+ }
700
+ return bestDelimiter;
701
+ }
702
+ /**
703
+ * Detect if first row is likely a header
704
+ */
705
+ detectHeader(rows) {
706
+ if (rows.length < 2) return false;
707
+ const firstRow = rows[0].values;
708
+ const secondRow = rows[1].values;
709
+ if (firstRow.reduce((sum, v) => sum + v.length, 0) / firstRow.length > secondRow.reduce((sum, v) => sum + v.length, 0) / secondRow.length * 1.5) return false;
710
+ const firstRowNumeric = firstRow.filter((v) => !isNaN(Number(v)) && v.trim() !== "").length;
711
+ return firstRow.length - firstRowNumeric >= firstRowNumeric;
712
+ }
713
+ /**
714
+ * Boost confidence if column name indicates PII
715
+ */
716
+ boostConfidenceFromColumnName(detections, columnName, piiIndicatorNames) {
717
+ if (!columnName) return detections;
718
+ const nameLower = columnName.toLowerCase().trim();
719
+ if (!piiIndicatorNames.some((indicator) => nameLower.includes(indicator.toLowerCase()))) return detections;
720
+ return detections.map((detection) => ({
721
+ ...detection,
722
+ confidence: Math.min(1, (detection.confidence || .5) * 1.2)
723
+ }));
724
+ }
725
+ /**
726
+ * Extract all cell values as text
727
+ */
728
+ extractText(input, options) {
729
+ const rows = this.parse(input, options);
730
+ const textParts = [];
731
+ for (const row of rows) for (const value of row.values) if (value.trim().length > 0) textParts.push(value);
732
+ return textParts.join(" ");
733
+ }
734
+ /**
735
+ * Get column statistics without full PII detection
736
+ */
737
+ getColumnInfo(input, options) {
738
+ const rows = this.parse(input, options);
739
+ if (rows.length === 0) return {
740
+ columnCount: 0,
741
+ rowCount: 0,
742
+ sampleRows: []
743
+ };
744
+ const opts = {
745
+ ...this.defaultOptions,
746
+ ...options
747
+ };
748
+ const hasHeader = opts.hasHeader !== void 0 ? opts.hasHeader : this.detectHeader(rows);
749
+ const headers = hasHeader && rows.length > 0 ? rows[0].values : void 0;
750
+ const dataRows = hasHeader ? rows.slice(1) : rows;
751
+ const sampleRows = dataRows.slice(0, 5).map((r) => r.values);
752
+ return {
753
+ columnCount: rows[0].values.length,
754
+ rowCount: dataRows.length,
755
+ headers,
756
+ sampleRows
757
+ };
758
+ }
759
+ };
760
+
761
+ //#endregion
762
+ //#region src/document/XlsxProcessor.ts
763
+ /**
764
+ * XLSX processor for spreadsheet data
765
+ */
766
+ var XlsxProcessor = class {
767
+ constructor() {
768
+ this.defaultOptions = {
769
+ piiIndicatorNames: [
770
+ "email",
771
+ "e-mail",
772
+ "mail",
773
+ "email_address",
774
+ "phone",
775
+ "tel",
776
+ "telephone",
777
+ "mobile",
778
+ "phone_number",
779
+ "ssn",
780
+ "social_security",
781
+ "social_security_number",
782
+ "address",
783
+ "street",
784
+ "street_address",
785
+ "city",
786
+ "zip",
787
+ "zipcode",
788
+ "postal",
789
+ "postcode",
790
+ "name",
791
+ "firstname",
792
+ "first_name",
793
+ "lastname",
794
+ "last_name",
795
+ "fullname",
796
+ "full_name",
797
+ "password",
798
+ "pwd",
799
+ "secret",
800
+ "token",
801
+ "api_key",
802
+ "card",
803
+ "credit_card",
804
+ "creditcard",
805
+ "card_number",
806
+ "account",
807
+ "account_number",
808
+ "iban",
809
+ "swift",
810
+ "passport",
811
+ "passport_number",
812
+ "license",
813
+ "licence",
814
+ "driver_license",
815
+ "dob",
816
+ "date_of_birth",
817
+ "birth_date",
818
+ "birthdate"
819
+ ],
820
+ preserveFormatting: true,
821
+ preserveFormulas: true
822
+ };
823
+ try {
824
+ this.xlsx = require("xlsx");
825
+ } catch {}
826
+ }
827
+ /**
828
+ * Check if XLSX support is available
829
+ */
830
+ isAvailable() {
831
+ return !!this.xlsx;
832
+ }
833
+ /**
834
+ * Parse XLSX from buffer
835
+ */
836
+ parse(buffer) {
837
+ if (!this.xlsx) throw new Error("[XlsxProcessor] XLSX support requires xlsx package. Install with: npm install xlsx");
838
+ try {
839
+ return this.xlsx.read(buffer, {
840
+ type: "buffer",
841
+ cellFormula: true,
842
+ cellStyles: true
843
+ });
844
+ } catch (error) {
845
+ throw new Error(`[XlsxProcessor] Failed to parse XLSX: ${error.message}`);
846
+ }
847
+ }
848
+ /**
849
+ * Detect PII in XLSX data
850
+ */
851
+ async detect(buffer, detector, options) {
852
+ if (!this.xlsx) throw new Error("[XlsxProcessor] XLSX support requires xlsx package. Install with: npm install xlsx");
853
+ const opts = {
854
+ ...this.defaultOptions,
855
+ ...options
856
+ };
857
+ const workbook = this.parse(buffer);
858
+ const sheetNames = this.getSheetNamesToProcess(workbook, opts);
859
+ const sheetResults = [];
860
+ const allDetections = [];
861
+ const allTypes = /* @__PURE__ */ new Set();
862
+ for (let sheetIndex = 0; sheetIndex < sheetNames.length; sheetIndex++) {
863
+ const sheetName = sheetNames[sheetIndex];
864
+ const sheet = workbook.Sheets[sheetName];
865
+ const sheetResult = await this.detectSheet(sheet, sheetName, sheetIndex, detector, opts);
866
+ sheetResults.push(sheetResult);
867
+ allDetections.push(...sheetResult.matchesByCell.flatMap((c) => c.matches));
868
+ sheetResult.matchesByCell.forEach((cell) => {
869
+ cell.matches.forEach((det) => allTypes.add(det.type));
870
+ });
871
+ }
872
+ const original = this.extractText(buffer, options);
873
+ const redactedBuffer = this.redact(buffer, {
874
+ original,
875
+ redacted: original,
876
+ detections: allDetections,
877
+ redactionMap: {},
878
+ stats: { piiCount: allDetections.length },
879
+ sheetResults,
880
+ sheetCount: sheetResults.length
881
+ }, options);
882
+ const redacted = this.extractText(redactedBuffer, options);
883
+ const redactionMap = {};
884
+ allDetections.forEach((det) => {
885
+ redactionMap[det.placeholder] = det.value;
886
+ });
887
+ return {
888
+ original,
889
+ redacted,
890
+ detections: allDetections,
891
+ redactionMap,
892
+ stats: { piiCount: allDetections.length },
893
+ sheetResults,
894
+ sheetCount: sheetResults.length
895
+ };
896
+ }
897
+ /**
898
+ * Detect PII in a single sheet
899
+ */
900
+ async detectSheet(sheet, sheetName, sheetIndex, detector, options) {
901
+ const range = this.xlsx.utils.decode_range(sheet["!ref"] || "A1");
902
+ const startRow = range.s.r;
903
+ const endRow = options.maxRows !== void 0 ? Math.min(range.e.r, startRow + options.maxRows - 1) : range.e.r;
904
+ const startCol = range.s.c;
905
+ const endCol = range.e.c;
906
+ const columnCount = endCol - startCol + 1;
907
+ const hasHeader = options.hasHeader !== void 0 ? options.hasHeader : this.detectHeader(sheet, range);
908
+ const headers = hasHeader ? this.getRowValues(sheet, startRow, startCol, endCol) : void 0;
909
+ const dataStartRow = hasHeader ? startRow + 1 : startRow;
910
+ const columnNameToIndex = /* @__PURE__ */ new Map();
911
+ if (headers) headers.forEach((header, index) => {
912
+ if (header) columnNameToIndex.set(header.toLowerCase().trim(), index);
913
+ });
914
+ const alwaysRedactCols = new Set(options.alwaysRedactColumns || []);
915
+ if (options.alwaysRedactColumnNames && headers) options.alwaysRedactColumnNames.forEach((name) => {
916
+ const index = columnNameToIndex.get(name.toLowerCase().trim());
917
+ if (index !== void 0) alwaysRedactCols.add(index);
918
+ });
919
+ const skipCols = new Set(options.skipColumns || []);
920
+ const columnStats = {};
921
+ for (let col = 0; col <= endCol - startCol; col++) columnStats[col] = {
922
+ columnIndex: col,
923
+ columnLetter: this.columnToLetter(col),
924
+ columnName: headers?.[col],
925
+ piiCount: 0,
926
+ piiPercentage: 0,
927
+ piiTypes: []
928
+ };
929
+ const matchesByCell = [];
930
+ for (let row = dataStartRow; row <= endRow; row++) for (let col = startCol; col <= endCol; col++) {
931
+ const colIndex = col - startCol;
932
+ if (skipCols.has(colIndex)) continue;
933
+ const cellRef = this.xlsx.utils.encode_cell({
934
+ r: row,
935
+ c: col
936
+ });
937
+ const cell = sheet[cellRef];
938
+ if (!cell) continue;
939
+ const cellValue = this.getCellValue(cell);
940
+ if (!cellValue) continue;
941
+ const cellFormula = cell.f;
942
+ if (alwaysRedactCols.has(colIndex)) {
943
+ const detection = {
944
+ type: "SENSITIVE_COLUMN",
945
+ value: cellValue,
946
+ placeholder: `[SENSITIVE_COLUMN_${colIndex}]`,
947
+ position: [0, cellValue.length],
948
+ severity: "high",
949
+ confidence: 1
950
+ };
951
+ matchesByCell.push({
952
+ cell: cellRef,
953
+ row: row + 1,
954
+ column: colIndex,
955
+ columnLetter: this.columnToLetter(colIndex),
956
+ columnName: headers?.[colIndex],
957
+ value: cellValue,
958
+ formula: cellFormula,
959
+ matches: [detection]
960
+ });
961
+ columnStats[colIndex].piiCount++;
962
+ continue;
963
+ }
964
+ const result = await detector.detect(cellValue);
965
+ if (result.detections.length > 0) {
966
+ const boostedDetections = this.boostConfidenceFromColumnName(result.detections, headers?.[colIndex], options.piiIndicatorNames || []);
967
+ matchesByCell.push({
968
+ cell: cellRef,
969
+ row: row + 1,
970
+ column: colIndex,
971
+ columnLetter: this.columnToLetter(colIndex),
972
+ columnName: headers?.[colIndex],
973
+ value: cellValue,
974
+ formula: cellFormula,
975
+ matches: boostedDetections
976
+ });
977
+ columnStats[colIndex].piiCount += boostedDetections.length;
978
+ const columnTypes = new Set(columnStats[colIndex].piiTypes);
979
+ boostedDetections.forEach((d) => columnTypes.add(d.type));
980
+ columnStats[colIndex].piiTypes = Array.from(columnTypes);
981
+ }
982
+ }
983
+ const dataRowCount = endRow - dataStartRow + 1;
984
+ for (let col = 0; col <= endCol - startCol; col++) {
985
+ const rowsWithPii = matchesByCell.filter((m) => m.column === col).length;
986
+ columnStats[col].piiPercentage = dataRowCount > 0 ? rowsWithPii / dataRowCount * 100 : 0;
987
+ }
988
+ return {
989
+ sheetName,
990
+ sheetIndex,
991
+ rowCount: dataRowCount,
992
+ columnCount,
993
+ headers: headers?.filter((h) => h !== void 0),
994
+ columnStats,
995
+ matchesByCell
996
+ };
997
+ }
998
+ /**
999
+ * Redact PII in XLSX data
1000
+ */
1001
+ redact(buffer, detectionResult, options) {
1002
+ if (!this.xlsx) throw new Error("[XlsxProcessor] XLSX support requires xlsx package. Install with: npm install xlsx");
1003
+ const opts = {
1004
+ ...this.defaultOptions,
1005
+ ...options
1006
+ };
1007
+ const workbook = this.parse(buffer);
1008
+ for (const sheetResult of detectionResult.sheetResults) {
1009
+ const sheet = workbook.Sheets[sheetResult.sheetName];
1010
+ for (const cellMatch of sheetResult.matchesByCell) {
1011
+ const cell = sheet[cellMatch.cell];
1012
+ if (!cell) continue;
1013
+ cell.v = "[REDACTED]";
1014
+ cell.w = "[REDACTED]";
1015
+ if (!opts.preserveFormulas) delete cell.f;
1016
+ cell.t = "s";
1017
+ }
1018
+ }
1019
+ return this.xlsx.write(workbook, {
1020
+ type: "buffer",
1021
+ bookType: "xlsx"
1022
+ });
1023
+ }
1024
+ /**
1025
+ * Get cell value as string
1026
+ */
1027
+ getCellValue(cell) {
1028
+ if (!cell) return "";
1029
+ if (cell.w !== void 0) return String(cell.w);
1030
+ if (cell.v !== void 0) return String(cell.v);
1031
+ return "";
1032
+ }
1033
+ /**
1034
+ * Get row values
1035
+ */
1036
+ getRowValues(sheet, row, startCol, endCol) {
1037
+ const values = [];
1038
+ for (let col = startCol; col <= endCol; col++) {
1039
+ const cell = sheet[this.xlsx.utils.encode_cell({
1040
+ r: row,
1041
+ c: col
1042
+ })];
1043
+ values.push(cell ? this.getCellValue(cell) : void 0);
1044
+ }
1045
+ return values;
1046
+ }
1047
+ /**
1048
+ * Detect if first row is likely a header
1049
+ */
1050
+ detectHeader(sheet, range) {
1051
+ const firstRow = this.getRowValues(sheet, range.s.r, range.s.c, range.e.c);
1052
+ const secondRow = range.s.r + 1 <= range.e.r ? this.getRowValues(sheet, range.s.r + 1, range.s.c, range.e.c) : null;
1053
+ if (!secondRow) return false;
1054
+ const firstRowValues = firstRow.filter((v) => v !== void 0);
1055
+ const secondRowValues = secondRow.filter((v) => v !== void 0);
1056
+ if (firstRowValues.length === 0 || secondRowValues.length === 0) return false;
1057
+ if (firstRowValues.reduce((sum, v) => sum + v.length, 0) / firstRowValues.length > secondRowValues.reduce((sum, v) => sum + v.length, 0) / secondRowValues.length * 1.5) return false;
1058
+ const firstRowNumeric = firstRowValues.filter((v) => !isNaN(Number(v)) && v.trim() !== "").length;
1059
+ return firstRowValues.length - firstRowNumeric >= firstRowNumeric;
1060
+ }
1061
+ /**
1062
+ * Convert column index to letter (0 = A, 25 = Z, 26 = AA)
1063
+ */
1064
+ columnToLetter(col) {
1065
+ let letter = "";
1066
+ while (col >= 0) {
1067
+ letter = String.fromCharCode(col % 26 + 65) + letter;
1068
+ col = Math.floor(col / 26) - 1;
1069
+ }
1070
+ return letter;
1071
+ }
1072
+ /**
1073
+ * Get sheet names to process based on options
1074
+ */
1075
+ getSheetNamesToProcess(workbook, options) {
1076
+ const allSheetNames = workbook.SheetNames;
1077
+ if (options.sheets && options.sheets.length > 0) return options.sheets.filter((name) => allSheetNames.includes(name));
1078
+ if (options.sheetIndices && options.sheetIndices.length > 0) return options.sheetIndices.filter((index) => index >= 0 && index < allSheetNames.length).map((index) => allSheetNames[index]);
1079
+ return allSheetNames;
1080
+ }
1081
+ /**
1082
+ * Boost confidence if column name indicates PII
1083
+ */
1084
+ boostConfidenceFromColumnName(detections, columnName, piiIndicatorNames) {
1085
+ if (!columnName) return detections;
1086
+ const nameLower = columnName.toLowerCase().trim();
1087
+ if (!piiIndicatorNames.some((indicator) => nameLower.includes(indicator.toLowerCase()))) return detections;
1088
+ return detections.map((detection) => ({
1089
+ ...detection,
1090
+ confidence: Math.min(1, (detection.confidence || .5) * 1.2)
1091
+ }));
1092
+ }
1093
+ /**
1094
+ * Extract all cell values as text
1095
+ */
1096
+ extractText(buffer, options) {
1097
+ if (!this.xlsx) throw new Error("[XlsxProcessor] XLSX support requires xlsx package. Install with: npm install xlsx");
1098
+ const workbook = this.parse(buffer);
1099
+ const opts = {
1100
+ ...this.defaultOptions,
1101
+ ...options
1102
+ };
1103
+ const sheetNames = this.getSheetNamesToProcess(workbook, opts);
1104
+ const textParts = [];
1105
+ for (const sheetName of sheetNames) {
1106
+ const sheet = workbook.Sheets[sheetName];
1107
+ const range = this.xlsx.utils.decode_range(sheet["!ref"] || "A1");
1108
+ for (let row = range.s.r; row <= range.e.r; row++) for (let col = range.s.c; col <= range.e.c; col++) {
1109
+ const cell = sheet[this.xlsx.utils.encode_cell({
1110
+ r: row,
1111
+ c: col
1112
+ })];
1113
+ if (cell) {
1114
+ const value = this.getCellValue(cell);
1115
+ if (value.trim().length > 0) textParts.push(value);
1116
+ }
1117
+ }
1118
+ }
1119
+ return textParts.join(" ");
1120
+ }
1121
+ /**
1122
+ * Get workbook metadata
1123
+ */
1124
+ getMetadata(buffer) {
1125
+ if (!this.xlsx) throw new Error("[XlsxProcessor] XLSX support requires xlsx package. Install with: npm install xlsx");
1126
+ const workbook = this.parse(buffer);
1127
+ return {
1128
+ sheetNames: workbook.SheetNames,
1129
+ sheetCount: workbook.SheetNames.length
1130
+ };
1131
+ }
1132
+ };
1133
+
1134
+ //#endregion
1135
+ //#region src/document/DocumentProcessor.ts
1136
+ /**
1137
+ * Document processor with optional PDF, DOCX, OCR, JSON, CSV, and XLSX support
1138
+ * Requires peer dependencies:
1139
+ * - pdf-parse (for PDF)
1140
+ * - mammoth (for DOCX)
1141
+ * - tesseract.js (for OCR/images)
1142
+ * - xlsx (for Excel/XLSX)
1143
+ */
1144
+ var DocumentProcessor = class {
1145
+ constructor() {
1146
+ try {
1147
+ this.pdfParse = require("pdf-parse");
1148
+ } catch {}
1149
+ try {
1150
+ this.mammoth = require("mammoth");
1151
+ } catch {}
1152
+ this.ocrProcessor = new OCRProcessor();
1153
+ this.jsonProcessor = new JsonProcessor();
1154
+ this.csvProcessor = new CsvProcessor();
1155
+ this.xlsxProcessor = new XlsxProcessor();
1156
+ }
1157
+ /**
1158
+ * Extract text from document buffer
1159
+ */
1160
+ async extractText(buffer, options) {
1161
+ const format = options?.format || this.detectFormat(buffer);
1162
+ if (!format) throw new Error("[DocumentProcessor] Unable to detect document format. Supported: PDF, DOCX, TXT, images (with OCR)");
1163
+ const maxSize = options?.maxSize || 50 * 1024 * 1024;
1164
+ if (buffer.length > maxSize) throw new Error(`[DocumentProcessor] Document size (${buffer.length} bytes) exceeds maximum (${maxSize} bytes)`);
1165
+ switch (format) {
1166
+ case "pdf": return this.extractPdfText(buffer, options);
1167
+ case "docx": return this.extractDocxText(buffer, options);
1168
+ case "txt": return buffer.toString("utf-8");
1169
+ case "image": return this.extractImageText(buffer, options);
1170
+ case "json": return this.extractJsonText(buffer, options);
1171
+ case "csv": return this.extractCsvText(buffer, options);
1172
+ case "xlsx": return this.extractXlsxText(buffer, options);
1173
+ default: throw new Error(`[DocumentProcessor] Unsupported format: ${format}`);
1174
+ }
1175
+ }
1176
+ /**
1177
+ * Get document metadata
1178
+ */
1179
+ async getMetadata(buffer, options) {
1180
+ const format = options?.format || this.detectFormat(buffer);
1181
+ if (!format) throw new Error("[DocumentProcessor] Unable to detect document format");
1182
+ switch (format) {
1183
+ case "pdf": return this.getPdfMetadata(buffer, options);
1184
+ case "docx": return this.getDocxMetadata(buffer, options);
1185
+ case "txt": return {
1186
+ format: "txt",
1187
+ pages: void 0
1188
+ };
1189
+ case "image": return this.getImageMetadata(buffer, options);
1190
+ case "json": return this.getJsonMetadata(buffer, options);
1191
+ case "csv": return this.getCsvMetadata(buffer, options);
1192
+ case "xlsx": return this.getXlsxMetadata(buffer, options);
1193
+ default: throw new Error(`[DocumentProcessor] Unsupported format: ${format}`);
1194
+ }
1195
+ }
1196
+ /**
1197
+ * Detect document format from buffer
1198
+ */
1199
+ detectFormat(buffer) {
1200
+ if (buffer.length < 4) return null;
1201
+ if (buffer.toString("utf-8", 0, 4) === "%PDF") return "pdf";
1202
+ if (buffer.length >= 8 && buffer[0] === 137 && buffer[1] === 80 && buffer[2] === 78 && buffer[3] === 71) return "image";
1203
+ if (buffer[0] === 255 && buffer[1] === 216 && buffer[2] === 255) return "image";
1204
+ if (buffer[0] === 73 && buffer[1] === 73 && buffer[2] === 42 && buffer[3] === 0 || buffer[0] === 77 && buffer[1] === 77 && buffer[2] === 0 && buffer[3] === 42) return "image";
1205
+ if (buffer[0] === 66 && buffer[1] === 77) return "image";
1206
+ if (buffer.length >= 12 && buffer[0] === 82 && buffer[1] === 73 && buffer[2] === 70 && buffer[3] === 70 && buffer[8] === 87 && buffer[9] === 69 && buffer[10] === 66 && buffer[11] === 80) return "image";
1207
+ if (buffer[0] === 80 && buffer[1] === 75) {
1208
+ const zipHeader = buffer.toString("utf-8", 0, Math.min(500, buffer.length));
1209
+ if (zipHeader.includes("word/") || zipHeader.includes("[Content_Types].xml")) return "docx";
1210
+ if (zipHeader.includes("xl/")) return "xlsx";
1211
+ }
1212
+ const text = buffer.toString("utf-8");
1213
+ const trimmed = text.trim();
1214
+ if (trimmed.startsWith("{") && trimmed.endsWith("}") || trimmed.startsWith("[") && trimmed.endsWith("]")) {
1215
+ if (this.jsonProcessor.isValid(buffer)) return "json";
1216
+ }
1217
+ const lines = text.split(/\r?\n/).slice(0, 5);
1218
+ if (lines.length >= 2) for (const delimiter of [
1219
+ ",",
1220
+ " ",
1221
+ ";",
1222
+ "|"
1223
+ ]) {
1224
+ const counts = lines.map((line) => (line.match(new RegExp(delimiter, "g")) || []).length);
1225
+ if (counts[0] > 0 && counts.every((c) => c === counts[0])) return "csv";
1226
+ }
1227
+ const sample = buffer.slice(0, Math.min(1e3, buffer.length));
1228
+ if (sample.filter((byte) => byte < 32 && byte !== 9 && byte !== 10 && byte !== 13).length < sample.length * .1) return "txt";
1229
+ return null;
1230
+ }
1231
+ /**
1232
+ * Check if format is supported
1233
+ */
1234
+ isFormatSupported(format) {
1235
+ switch (format) {
1236
+ case "pdf": return !!this.pdfParse;
1237
+ case "docx": return !!this.mammoth;
1238
+ case "txt": return true;
1239
+ case "image": return this.ocrProcessor.isAvailable();
1240
+ case "json": return true;
1241
+ case "csv": return true;
1242
+ case "xlsx": return this.xlsxProcessor.isAvailable();
1243
+ default: return false;
1244
+ }
1245
+ }
1246
+ /**
1247
+ * Extract text from PDF
1248
+ */
1249
+ async extractPdfText(buffer, options) {
1250
+ if (!this.pdfParse) throw new Error("[DocumentProcessor] PDF support requires pdf-parse. Install with: npm install pdf-parse");
1251
+ try {
1252
+ const data = await this.pdfParse(buffer, {
1253
+ password: options?.password,
1254
+ max: options?.pages ? Math.max(...options.pages) : void 0
1255
+ });
1256
+ if (options?.pages) return data.text;
1257
+ return data.text || "";
1258
+ } catch (error) {
1259
+ throw new Error(`[DocumentProcessor] PDF extraction failed: ${error.message}`);
1260
+ }
1261
+ }
1262
+ /**
1263
+ * Extract text from DOCX
1264
+ */
1265
+ async extractDocxText(buffer, _options) {
1266
+ if (!this.mammoth) throw new Error("[DocumentProcessor] DOCX support requires mammoth. Install with: npm install mammoth");
1267
+ try {
1268
+ return (await this.mammoth.extractRawText({ buffer })).value || "";
1269
+ } catch (error) {
1270
+ throw new Error(`[DocumentProcessor] DOCX extraction failed: ${error.message}`);
1271
+ }
1272
+ }
1273
+ /**
1274
+ * Get PDF metadata
1275
+ */
1276
+ async getPdfMetadata(buffer, _options) {
1277
+ if (!this.pdfParse) throw new Error("[DocumentProcessor] PDF support requires pdf-parse. Install with: npm install pdf-parse");
1278
+ try {
1279
+ const data = await this.pdfParse(buffer, { password: _options?.password });
1280
+ return {
1281
+ format: "pdf",
1282
+ pages: data.numpages,
1283
+ title: data.info?.Title,
1284
+ author: data.info?.Author,
1285
+ creationDate: data.info?.CreationDate ? new Date(data.info.CreationDate) : void 0,
1286
+ modifiedDate: data.info?.ModDate ? new Date(data.info.ModDate) : void 0,
1287
+ custom: data.info
1288
+ };
1289
+ } catch (error) {
1290
+ throw new Error(`[DocumentProcessor] PDF metadata extraction failed: ${error.message}`);
1291
+ }
1292
+ }
1293
+ /**
1294
+ * Get DOCX metadata
1295
+ */
1296
+ async getDocxMetadata(_buffer, _options) {
1297
+ return {
1298
+ format: "docx",
1299
+ pages: void 0
1300
+ };
1301
+ }
1302
+ /**
1303
+ * Extract text from image using OCR
1304
+ */
1305
+ async extractImageText(buffer, options) {
1306
+ if (!this.ocrProcessor.isAvailable()) throw new Error("[DocumentProcessor] Image/OCR support requires tesseract.js. Install with: npm install tesseract.js");
1307
+ try {
1308
+ return (await this.ocrProcessor.recognizeText(buffer, options?.ocrOptions)).text;
1309
+ } catch (error) {
1310
+ throw new Error(`[DocumentProcessor] Image text extraction failed: ${error.message}`);
1311
+ }
1312
+ }
1313
+ /**
1314
+ * Get image metadata
1315
+ */
1316
+ async getImageMetadata(buffer, options) {
1317
+ if (!this.ocrProcessor.isAvailable()) return {
1318
+ format: "image",
1319
+ pages: void 0,
1320
+ usedOCR: false
1321
+ };
1322
+ try {
1323
+ return {
1324
+ format: "image",
1325
+ pages: void 0,
1326
+ usedOCR: true,
1327
+ ocrConfidence: (await this.ocrProcessor.recognizeText(buffer, options?.ocrOptions)).confidence
1328
+ };
1329
+ } catch {
1330
+ return {
1331
+ format: "image",
1332
+ pages: void 0,
1333
+ usedOCR: false
1334
+ };
1335
+ }
1336
+ }
1337
+ /**
1338
+ * Extract text from JSON
1339
+ */
1340
+ async extractJsonText(buffer, _options) {
1341
+ try {
1342
+ return this.jsonProcessor.extractText(buffer);
1343
+ } catch (error) {
1344
+ throw new Error(`[DocumentProcessor] JSON extraction failed: ${error.message}`);
1345
+ }
1346
+ }
1347
+ /**
1348
+ * Extract text from CSV
1349
+ */
1350
+ async extractCsvText(buffer, _options) {
1351
+ try {
1352
+ return this.csvProcessor.extractText(buffer);
1353
+ } catch (error) {
1354
+ throw new Error(`[DocumentProcessor] CSV extraction failed: ${error.message}`);
1355
+ }
1356
+ }
1357
+ /**
1358
+ * Extract text from XLSX
1359
+ */
1360
+ async extractXlsxText(buffer, _options) {
1361
+ if (!this.xlsxProcessor.isAvailable()) throw new Error("[DocumentProcessor] XLSX support requires xlsx package. Install with: npm install xlsx");
1362
+ try {
1363
+ return this.xlsxProcessor.extractText(buffer);
1364
+ } catch (error) {
1365
+ throw new Error(`[DocumentProcessor] XLSX extraction failed: ${error.message}`);
1366
+ }
1367
+ }
1368
+ /**
1369
+ * Get JSON metadata
1370
+ */
1371
+ async getJsonMetadata(buffer, _options) {
1372
+ try {
1373
+ const data = this.jsonProcessor.parse(buffer);
1374
+ const isArray = Array.isArray(data);
1375
+ return {
1376
+ format: "json",
1377
+ pages: void 0,
1378
+ custom: {
1379
+ isArray,
1380
+ itemCount: isArray ? data.length : Object.keys(data).length
1381
+ }
1382
+ };
1383
+ } catch {
1384
+ return {
1385
+ format: "json",
1386
+ pages: void 0
1387
+ };
1388
+ }
1389
+ }
1390
+ /**
1391
+ * Get CSV metadata
1392
+ */
1393
+ async getCsvMetadata(buffer, _options) {
1394
+ try {
1395
+ const info = this.csvProcessor.getColumnInfo(buffer);
1396
+ return {
1397
+ format: "csv",
1398
+ pages: void 0,
1399
+ custom: {
1400
+ rowCount: info.rowCount,
1401
+ columnCount: info.columnCount,
1402
+ headers: info.headers
1403
+ }
1404
+ };
1405
+ } catch {
1406
+ return {
1407
+ format: "csv",
1408
+ pages: void 0
1409
+ };
1410
+ }
1411
+ }
1412
+ /**
1413
+ * Get XLSX metadata
1414
+ */
1415
+ async getXlsxMetadata(buffer, _options) {
1416
+ if (!this.xlsxProcessor.isAvailable()) return {
1417
+ format: "xlsx",
1418
+ pages: void 0
1419
+ };
1420
+ try {
1421
+ const metadata = this.xlsxProcessor.getMetadata(buffer);
1422
+ return {
1423
+ format: "xlsx",
1424
+ pages: void 0,
1425
+ custom: {
1426
+ sheetNames: metadata.sheetNames,
1427
+ sheetCount: metadata.sheetCount
1428
+ }
1429
+ };
1430
+ } catch {
1431
+ return {
1432
+ format: "xlsx",
1433
+ pages: void 0
1434
+ };
1435
+ }
1436
+ }
1437
+ /**
1438
+ * Get OCR processor instance
1439
+ */
1440
+ getOCRProcessor() {
1441
+ return this.ocrProcessor;
1442
+ }
1443
+ /**
1444
+ * Get JSON processor instance
1445
+ */
1446
+ getJsonProcessor() {
1447
+ return this.jsonProcessor;
1448
+ }
1449
+ /**
1450
+ * Get CSV processor instance
1451
+ */
1452
+ getCsvProcessor() {
1453
+ return this.csvProcessor;
1454
+ }
1455
+ /**
1456
+ * Get XLSX processor instance
1457
+ */
1458
+ getXlsxProcessor() {
1459
+ return this.xlsxProcessor;
1460
+ }
1461
+ };
1462
+ /**
1463
+ * Create a document processor instance
1464
+ */
1465
+ function createDocumentProcessor() {
1466
+ return new DocumentProcessor();
1467
+ }
1468
+
1469
+ //#endregion
1470
+ exports.createDocumentProcessor = createDocumentProcessor;