rs-chunks 0.6.4

Fast, high-fidelity document chunking for RAG — a pure-Rust engine covering 36 file formats (Office, OpenDocument, PDF, email, ebooks, notebooks, and more).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
//! Source-agnostic dispatch: route a file to the right engine by extension,
//! mirroring the Python `get_chunks()` routing (including the delimited/
//! spreadsheet special-casing) so behaviour matches the reference package.
//!
//! Every public entry point here runs the parse behind a `catch_unwind`
//! boundary: a panic anywhere in the engine (or a third-party parser) is
//! converted into [`ChunkError::Parse`] instead of unwinding into the caller.

use std::path::Path;

use crate::chunk::Chunk;
use crate::error::{ChunkError, Result};
use crate::formats;

/// Run `f` behind a panic boundary, converting any panic into
/// [`ChunkError::Parse`] so adversarial inputs can never unwind across the
/// public dispatch API.
///
/// `AssertUnwindSafe` is justified: the closure only captures shared references
/// to caller-owned input (`&[u8]` / `&str`) plus `Copy` scalars, the engine
/// keeps no global mutable state, and on the panic path every partially-built
/// value is owned by the closure and dropped — nothing observable is left in a
/// broken state.
fn catch_parser_panics<T>(f: impl FnOnce() -> Result<T>) -> Result<T> {
    match std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)) {
        Ok(result) => result,
        Err(payload) => {
            let msg = crate::error::panic_message(payload);
            Err(ChunkError::Parse(format!("internal parser panic: {msg}")))
        }
    }
}

/// Chunk a document supplied as raw bytes. `filename` is used only for extension
/// detection (routing) — never persisted under that name.
///
/// Routes to each format's no-filesystem `chunk_from_bytes`; unsupported
/// extensions return [`ChunkError::Unsupported`]. See [`get_chunks`] for the
/// `sentences_per_chunk == 3` spreadsheet sentinel.
pub fn get_chunks_from_bytes(
    data: &[u8],
    filename: &str,
    mode: &str,
    window_size: usize,
    overlap: usize,
    sentences_per_chunk: usize,
    paragraphs_per_page: usize,
) -> Result<Vec<Chunk>> {
    catch_parser_panics(|| {
        get_chunks_from_bytes_inner(
            data,
            filename,
            mode,
            window_size,
            overlap,
            sentences_per_chunk,
            paragraphs_per_page,
        )
    })
}

fn get_chunks_from_bytes_inner(
    data: &[u8],
    filename: &str,
    mode: &str,
    window_size: usize,
    overlap: usize,
    sentences_per_chunk: usize,
    paragraphs_per_page: usize,
) -> Result<Vec<Chunk>> {
    let ext = ext_of(filename);
    match ext.as_str() {
        "csv" | "tsv" => {
            let csv_mode = if mode == "default" { "row" } else { mode };
            let rows_per_chunk = if csv_mode == "page_aware" {
                paragraphs_per_page
            } else {
                csv_rows_per_chunk(sentences_per_chunk)
            };
            let delimiter = if ext == "tsv" { Some(b'\t') } else { None };
            formats::csv::chunk_from_bytes(
                data,
                csv_mode,
                rows_per_chunk,
                window_size,
                overlap,
                true,
                delimiter,
                "auto",
                true,
            )
        }
        "xlsx" | "xls" | "xlsm" | "xlsb" | "ods" | "xltx" | "xltm" => {
            let xmode = if mode == "default" { "row" } else { mode };
            check_spreadsheet_page_arg(xmode, paragraphs_per_page)?;
            // Sentinel (parity with the Python default): 3 == "caller left the
            // default", mapped to rows_per_chunk = 1. See `get_chunks`.
            let rows_per_chunk = if sentences_per_chunk == 3 {
                1
            } else {
                sentences_per_chunk
            };
            formats::xlsx::chunk_from_bytes(
                data,
                &ext,
                xmode,
                rows_per_chunk,
                window_size,
                overlap,
                true,
                Vec::new(),
                true,
                2000,
            )
        }
        "md" => formats::md::chunk_from_bytes(
            data,
            mode,
            window_size,
            overlap,
            sentences_per_chunk,
            paragraphs_per_page,
        ),
        "txt" => formats::txt::chunk_from_bytes(
            data,
            mode,
            window_size,
            overlap,
            sentences_per_chunk,
            paragraphs_per_page,
        ),
        "html" | "htm" => formats::html::chunk_from_bytes(
            data,
            mode,
            window_size,
            overlap,
            sentences_per_chunk,
            paragraphs_per_page,
        ),
        "docx" | "docm" | "dotx" | "dotm" => formats::docx::chunk_from_bytes(
            data,
            mode,
            window_size,
            overlap,
            sentences_per_chunk,
            paragraphs_per_page,
        ),
        "pptx" | "potx" | "potm" | "ppsx" | "ppsm" => formats::pptx::chunk_from_bytes(
            data,
            mode,
            window_size,
            overlap,
            sentences_per_chunk,
            paragraphs_per_page,
        ),
        "json" | "jsonl" | "ndjson" => formats::json::chunk_from_bytes(
            data,
            filename,
            mode,
            window_size,
            overlap,
            sentences_per_chunk,
            paragraphs_per_page,
        ),
        "eml" | "mbox" => formats::eml::chunk_from_bytes(
            data,
            filename,
            mode,
            window_size,
            overlap,
            sentences_per_chunk,
            paragraphs_per_page,
        ),
        "odt" | "odp" => formats::odf::chunk_from_bytes(
            data,
            filename,
            mode,
            window_size,
            overlap,
            sentences_per_chunk,
            paragraphs_per_page,
        ),
        "ipynb" => formats::ipynb::chunk_from_bytes(
            data,
            mode,
            window_size,
            overlap,
            sentences_per_chunk,
            paragraphs_per_page,
        ),
        "rtf" => formats::rtf::chunk_from_bytes(
            data,
            mode,
            window_size,
            overlap,
            sentences_per_chunk,
            paragraphs_per_page,
        ),
        "epub" => formats::epub::chunk_from_bytes(
            data,
            mode,
            window_size,
            overlap,
            sentences_per_chunk,
            paragraphs_per_page,
        ),
        "msg" => formats::msg::chunk_from_bytes(
            data,
            mode,
            window_size,
            overlap,
            sentences_per_chunk,
            paragraphs_per_page,
        ),
        "doc" => formats::doc::chunk_from_bytes(
            data,
            filename,
            mode,
            window_size,
            overlap,
            sentences_per_chunk,
            paragraphs_per_page,
        ),
        "ppt" => formats::ppt::chunk_from_bytes(
            data,
            filename,
            mode,
            window_size,
            overlap,
            sentences_per_chunk,
            paragraphs_per_page,
        ),
        "pdf" => formats::pdf::chunk_from_bytes(
            data,
            mode,
            window_size,
            overlap,
            sentences_per_chunk,
            paragraphs_per_page,
        ),
        other => Err(ChunkError::Unsupported(format!(
            "Unsupported file type '.{other}'"
        ))),
    }
}

/// Convert bytes to Markdown; see [`get_chunks_from_bytes`] for the routing note.
pub fn get_markdown_from_bytes(data: &[u8], filename: &str) -> Result<String> {
    catch_parser_panics(|| get_markdown_from_bytes_inner(data, filename))
}

fn get_markdown_from_bytes_inner(data: &[u8], filename: &str) -> Result<String> {
    let ext = ext_of(filename);
    match ext.as_str() {
        "csv" => formats::csv::to_markdown_from_bytes(data, None, "auto"),
        "tsv" => formats::csv::to_markdown_from_bytes(data, Some(b'\t'), "auto"),
        "xlsx" | "xls" | "xlsm" | "xlsb" | "ods" | "xltx" | "xltm" => {
            formats::xlsx::to_markdown_from_bytes(data, &ext)
        }
        "md" => formats::md::to_markdown_from_bytes(data),
        "txt" => formats::txt::to_markdown_from_bytes(data),
        "html" | "htm" => formats::html::to_markdown_from_bytes(data),
        "docx" | "docm" | "dotx" | "dotm" => formats::docx::to_markdown_from_bytes(data),
        "pptx" | "potx" | "potm" | "ppsx" | "ppsm" => formats::pptx::to_markdown_from_bytes(data),
        "json" | "jsonl" | "ndjson" => formats::json::to_markdown_from_bytes(data, filename),
        "eml" | "mbox" => formats::eml::to_markdown_from_bytes(data, filename),
        "odt" | "odp" => formats::odf::to_markdown_from_bytes(data, filename),
        "ipynb" => formats::ipynb::to_markdown_from_bytes(data),
        "rtf" => formats::rtf::to_markdown_from_bytes(data),
        "epub" => formats::epub::to_markdown_from_bytes(data),
        "msg" => formats::msg::to_markdown_from_bytes(data),
        "doc" => formats::doc::to_markdown_from_bytes(data),
        "ppt" => formats::ppt::to_markdown_from_bytes(data),
        "pdf" => formats::pdf::to_markdown_from_bytes(data),
        other => Err(ChunkError::Unsupported(format!(
            "get_markdown does not support '.{other}'"
        ))),
    }
}

/// Chunk bytes and also return extracted image bytes (`list_images=True`).
/// Formats without embedded-image support return an empty image list and the
/// same chunks as [`get_chunks_from_bytes`].
#[allow(clippy::too_many_arguments)]
pub fn get_chunks_with_images_from_bytes(
    data: &[u8],
    filename: &str,
    mode: &str,
    window_size: usize,
    overlap: usize,
    sentences_per_chunk: usize,
    paragraphs_per_page: usize,
) -> Result<crate::chunk::ChunksWithImages> {
    catch_parser_panics(|| {
        get_chunks_with_images_from_bytes_inner(
            data,
            filename,
            mode,
            window_size,
            overlap,
            sentences_per_chunk,
            paragraphs_per_page,
        )
    })
}

#[allow(clippy::too_many_arguments)]
fn get_chunks_with_images_from_bytes_inner(
    data: &[u8],
    filename: &str,
    mode: &str,
    window_size: usize,
    overlap: usize,
    sentences_per_chunk: usize,
    paragraphs_per_page: usize,
) -> Result<crate::chunk::ChunksWithImages> {
    let ext = ext_of(filename);
    match ext.as_str() {
        "xlsx" | "xls" | "xlsm" | "xlsb" | "ods" | "xltx" | "xltm" => {
            let xmode = if mode == "default" { "row" } else { mode };
            check_spreadsheet_page_arg(xmode, paragraphs_per_page)?;
            // Sentinel (parity with the Python default): 3 == "caller left the
            // default", mapped to rows_per_chunk = 1. See `get_chunks`.
            let rows_per_chunk = if sentences_per_chunk == 3 {
                1
            } else {
                sentences_per_chunk
            };
            formats::xlsx::chunk_with_images_from_bytes(
                data,
                &ext,
                xmode,
                rows_per_chunk,
                window_size,
                overlap,
                true,
                Vec::new(),
                true,
                2000,
            )
        }
        "html" | "htm" => formats::html::chunk_with_images_from_bytes(
            data,
            mode,
            window_size,
            overlap,
            sentences_per_chunk,
            paragraphs_per_page,
        ),
        "docx" | "docm" | "dotx" | "dotm" => formats::docx::chunk_with_images_from_bytes(
            data,
            mode,
            window_size,
            overlap,
            sentences_per_chunk,
            paragraphs_per_page,
        ),
        "pptx" | "potx" | "potm" | "ppsx" | "ppsm" => formats::pptx::chunk_with_images_from_bytes(
            data,
            mode,
            window_size,
            overlap,
            sentences_per_chunk,
            paragraphs_per_page,
        ),
        "eml" | "mbox" => formats::eml::chunk_with_images_from_bytes(
            data,
            filename,
            mode,
            window_size,
            overlap,
            sentences_per_chunk,
            paragraphs_per_page,
        ),
        "msg" => formats::msg::chunk_with_images_from_bytes(
            data,
            mode,
            window_size,
            overlap,
            sentences_per_chunk,
            paragraphs_per_page,
        ),
        "odt" | "odp" => formats::odf::chunk_with_images_from_bytes(
            data,
            filename,
            mode,
            window_size,
            overlap,
            sentences_per_chunk,
            paragraphs_per_page,
        ),
        "ipynb" => formats::ipynb::chunk_with_images_from_bytes(
            data,
            mode,
            window_size,
            overlap,
            sentences_per_chunk,
            paragraphs_per_page,
        ),
        "epub" => formats::epub::chunk_with_images_from_bytes(
            data,
            mode,
            window_size,
            overlap,
            sentences_per_chunk,
            paragraphs_per_page,
        ),
        "doc" => formats::doc::chunk_with_images_from_bytes(
            data,
            filename,
            mode,
            window_size,
            overlap,
            sentences_per_chunk,
            paragraphs_per_page,
        ),
        "ppt" => formats::ppt::chunk_with_images_from_bytes(
            data,
            filename,
            mode,
            window_size,
            overlap,
            sentences_per_chunk,
            paragraphs_per_page,
        ),
        "pdf" => formats::pdf::chunk_with_images_from_bytes(
            data,
            mode,
            window_size,
            overlap,
            sentences_per_chunk,
            paragraphs_per_page,
        ),
        // No embedded-image support: chunks only, empty image list.
        _ => Ok((
            get_chunks_from_bytes_inner(
                data,
                filename,
                mode,
                window_size,
                overlap,
                sentences_per_chunk,
                paragraphs_per_page,
            )?,
            Vec::new(),
        )),
    }
}

/// Convert bytes to Markdown and return extracted image bytes (`list_images=True`).
pub fn get_markdown_with_images_from_bytes(
    data: &[u8],
    filename: &str,
) -> Result<crate::chunk::MarkdownWithImages> {
    catch_parser_panics(|| get_markdown_with_images_from_bytes_inner(data, filename))
}

fn get_markdown_with_images_from_bytes_inner(
    data: &[u8],
    filename: &str,
) -> Result<crate::chunk::MarkdownWithImages> {
    let ext = ext_of(filename);
    match ext.as_str() {
        "xlsx" | "xls" | "xlsm" | "xlsb" | "ods" | "xltx" | "xltm" => {
            formats::xlsx::to_markdown_with_images_from_bytes(data, &ext)
        }
        "html" | "htm" => formats::html::to_markdown_with_images_from_bytes(data),
        "docx" | "docm" | "dotx" | "dotm" => {
            formats::docx::to_markdown_with_images_from_bytes(data)
        }
        "pptx" | "potx" | "potm" | "ppsx" | "ppsm" => {
            formats::pptx::to_markdown_with_images_from_bytes(data)
        }
        "eml" | "mbox" => formats::eml::to_markdown_with_images_from_bytes(data, filename),
        "msg" => formats::msg::to_markdown_with_images_from_bytes(data),
        "odt" | "odp" => formats::odf::to_markdown_with_images_from_bytes(data, filename),
        "ipynb" => formats::ipynb::to_markdown_with_images_from_bytes(data),
        "epub" => formats::epub::to_markdown_with_images_from_bytes(data),
        "doc" => formats::doc::to_markdown_with_images_from_bytes(data),
        "ppt" => formats::ppt::to_markdown_with_images_from_bytes(data),
        "pdf" => formats::pdf::to_markdown_with_images_from_bytes(data),
        _ => Ok((get_markdown_from_bytes_inner(data, filename)?, Vec::new())),
    }
}

fn ext_of(file_path: &str) -> String {
    Path::new(file_path)
        .extension()
        .and_then(|e| e.to_str())
        .map(|e| e.to_ascii_lowercase())
        .unwrap_or_default()
}

fn csv_rows_per_chunk(sentences_per_chunk: usize) -> usize {
    sentences_per_chunk.max(1)
}

/// Reject `paragraphs_per_page == 0` for the spreadsheet family.
///
/// Spreadsheets paginate by `rows_per_chunk`, so the arms below map
/// `sentences_per_chunk` and drop `paragraphs_per_page` entirely — which meant
/// `page_aware` with `0` was silently accepted here while every other format
/// rejects it, and three docs pages promise it is rejected. The parameter stays
/// *ignored* (a spreadsheet page is a sheet region, not a unit count); only an
/// unusable value is now an error.
///
/// Mode-scoped exactly like [`crate::options::validate_mode_args`]: a value is
/// only required to be usable by the mode that reads it, so `0` in `row`/
/// `sheet`/`table` remains fine — as it is for every other format.
fn check_spreadsheet_page_arg(mode: &str, paragraphs_per_page: usize) -> Result<()> {
    if mode == "page_aware" && paragraphs_per_page == 0 {
        return Err(ChunkError::InvalidArg(
            "paragraphs_per_page must be greater than 0".to_string(),
        ));
    }
    Ok(())
}

/// Chunk any supported document by path. `mode` is passed through to the engine
/// ("default" selects each format's natural strategy); the delimited formats map
/// it onto their row/window/page strategies exactly like the Python entry point.
///
/// # The `sentences_per_chunk == 3` spreadsheet sentinel
///
/// For spreadsheet extensions (`xlsx`/`xls`/`xlsm`/`xlsb`/`ods`/`xltx`/`xltm`)
/// the value `3` — the Python API's *default* for `sentences_per_chunk` — is
/// treated as "caller didn't ask" and mapped to `rows_per_chunk = 1`, the
/// spreadsheet default. This mirrors the reference Python `get_chunks()`
/// exactly and is a deliberate parity constraint. The consequence: a caller
/// who *deliberately* wants 3 rows per chunk cannot express it through this
/// entry point (3 is unreachable); use `formats::xlsx::chunk` /
/// `chunk_with_options` directly, which take `rows_per_chunk` verbatim.
pub fn get_chunks(
    file_path: &str,
    mode: &str,
    window_size: usize,
    overlap: usize,
    sentences_per_chunk: usize,
    paragraphs_per_page: usize,
) -> Result<Vec<Chunk>> {
    catch_parser_panics(|| {
        get_chunks_inner(
            file_path,
            mode,
            window_size,
            overlap,
            sentences_per_chunk,
            paragraphs_per_page,
        )
    })
}

fn get_chunks_inner(
    file_path: &str,
    mode: &str,
    window_size: usize,
    overlap: usize,
    sentences_per_chunk: usize,
    paragraphs_per_page: usize,
) -> Result<Vec<Chunk>> {
    let ext = ext_of(file_path);
    match ext.as_str() {
        // ── Delimited text ──────────────────────────────────────────────
        "csv" | "tsv" => {
            let csv_mode = if mode == "default" { "row" } else { mode };
            let rows_per_chunk = if csv_mode == "page_aware" {
                paragraphs_per_page
            } else {
                csv_rows_per_chunk(sentences_per_chunk)
            };
            let delimiter = if ext == "tsv" { Some(b'\t') } else { None };
            formats::csv::chunk(
                file_path,
                csv_mode,
                rows_per_chunk,
                window_size,
                overlap,
                true,
                delimiter,
                "auto",
                true,
            )
        }
        // ── Spreadsheets (calamine) ─────────────────────────────────────
        "xlsx" | "xls" | "xlsm" | "xlsb" | "ods" | "xltx" | "xltm" => {
            let xmode = if mode == "default" { "row" } else { mode };
            check_spreadsheet_page_arg(xmode, paragraphs_per_page)?;
            // Sentinel (parity with the Python default): 3 == "caller left the
            // default", mapped to rows_per_chunk = 1. A deliberate 3 is
            // unreachable here — see the doc comment on `get_chunks`.
            let rows_per_chunk = if sentences_per_chunk == 3 {
                1
            } else {
                sentences_per_chunk
            };
            formats::xlsx::chunk(
                file_path,
                xmode,
                rows_per_chunk,
                window_size,
                overlap,
                true,
                Vec::new(),
                true,
                2000,
            )
        }
        "doc" => formats::doc::chunk(
            file_path,
            mode,
            window_size,
            overlap,
            sentences_per_chunk,
            paragraphs_per_page,
        ),
        // ── Word OOXML ──────────────────────────────────────────────────
        "docx" | "docm" | "dotx" | "dotm" => formats::docx::chunk(
            file_path,
            mode,
            window_size,
            overlap,
            sentences_per_chunk,
            paragraphs_per_page,
        ),
        // ── Prose / markdown-pipeline formats ───────────────────────────
        "ppt" => formats::ppt::chunk(
            file_path,
            mode,
            window_size,
            overlap,
            sentences_per_chunk,
            paragraphs_per_page,
        ),
        "pptx" | "potx" | "potm" | "ppsx" | "ppsm" => formats::pptx::chunk(
            file_path,
            mode,
            window_size,
            overlap,
            sentences_per_chunk,
            paragraphs_per_page,
        ),
        "md" => formats::md::chunk(
            file_path,
            mode,
            window_size,
            overlap,
            sentences_per_chunk,
            paragraphs_per_page,
        ),
        "txt" => formats::txt::chunk(
            file_path,
            mode,
            window_size,
            overlap,
            sentences_per_chunk,
            paragraphs_per_page,
        ),
        "html" | "htm" => formats::html::chunk(
            file_path,
            mode,
            window_size,
            overlap,
            sentences_per_chunk,
            paragraphs_per_page,
        ),
        "json" | "jsonl" | "ndjson" => formats::json::chunk(
            file_path,
            mode,
            window_size,
            overlap,
            sentences_per_chunk,
            paragraphs_per_page,
        ),
        "eml" | "mbox" => formats::eml::chunk(
            file_path,
            mode,
            window_size,
            overlap,
            sentences_per_chunk,
            paragraphs_per_page,
        ),
        "odt" | "odp" => formats::odf::chunk(
            file_path,
            mode,
            window_size,
            overlap,
            sentences_per_chunk,
            paragraphs_per_page,
        ),
        "msg" => formats::msg::chunk(
            file_path,
            mode,
            window_size,
            overlap,
            sentences_per_chunk,
            paragraphs_per_page,
        ),
        "ipynb" => formats::ipynb::chunk(
            file_path,
            mode,
            window_size,
            overlap,
            sentences_per_chunk,
            paragraphs_per_page,
        ),
        "rtf" => formats::rtf::chunk(
            file_path,
            mode,
            window_size,
            overlap,
            sentences_per_chunk,
            paragraphs_per_page,
        ),
        "pdf" => formats::pdf::chunk(
            file_path,
            mode,
            window_size,
            overlap,
            sentences_per_chunk,
            paragraphs_per_page,
        ),
        "epub" => formats::epub::chunk(
            file_path,
            mode,
            window_size,
            overlap,
            sentences_per_chunk,
            paragraphs_per_page,
        ),
        other => Err(ChunkError::Unsupported(format!(
            "Unsupported file type '.{other}'"
        ))),
    }
}

/// Convert a supported document to Markdown by path.
pub fn get_markdown(file_path: &str) -> Result<String> {
    catch_parser_panics(|| get_markdown_inner(file_path))
}

fn get_markdown_inner(file_path: &str) -> Result<String> {
    let ext = ext_of(file_path);
    match ext.as_str() {
        "csv" | "tsv" => {
            let delimiter = if ext == "tsv" { Some(b'\t') } else { None };
            formats::csv::to_markdown(file_path, delimiter, "auto")
        }
        "xlsx" | "xls" | "xlsm" | "xlsb" | "ods" | "xltx" | "xltm" => {
            formats::xlsx::to_markdown(file_path)
        }
        "doc" => formats::doc::to_markdown(file_path),
        "docx" | "docm" | "dotx" | "dotm" => formats::docx::to_markdown(file_path),
        "ppt" => formats::ppt::to_markdown(file_path),
        "pptx" | "potx" | "potm" | "ppsx" | "ppsm" => formats::pptx::to_markdown(file_path),
        "md" => formats::md::to_markdown(file_path),
        "txt" => formats::txt::to_markdown(file_path),
        "html" | "htm" => formats::html::to_markdown(file_path),
        "json" | "jsonl" | "ndjson" => formats::json::to_markdown(file_path),
        "eml" | "mbox" => formats::eml::to_markdown(file_path),
        "odt" | "odp" => formats::odf::to_markdown(file_path),
        "msg" => formats::msg::to_markdown(file_path),
        "ipynb" => formats::ipynb::to_markdown(file_path),
        "rtf" => formats::rtf::to_markdown(file_path),
        "pdf" => formats::pdf::to_markdown(file_path),
        "epub" => formats::epub::to_markdown(file_path),
        other => Err(ChunkError::Unsupported(format!(
            "get_markdown does not support '.{other}'"
        ))),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn panic_boundary_converts_panics_to_parse_errors() {
        let err = catch_parser_panics::<()>(|| panic!("boom at offset 42")).unwrap_err();
        match err {
            ChunkError::Parse(m) => {
                assert!(
                    m.contains("internal parser panic"),
                    "unexpected message: {m}"
                );
                assert!(m.contains("boom at offset 42"), "payload lost: {m}");
            }
            other => panic!("expected Parse, got {other:?}"),
        }
    }

    #[test]
    fn panic_boundary_passes_results_through() {
        assert!(catch_parser_panics(|| Ok(7)).is_ok_and(|v| v == 7));
        assert!(matches!(
            catch_parser_panics::<()>(|| Err(ChunkError::InvalidArg("x".into()))),
            Err(ChunkError::InvalidArg(_))
        ));
    }
}