sheeter-engine 0.5.0

A CLI tool for converting data files between formats. v0.1.0 supports CSV <-> JSON.
Documentation
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
//! Sheeter is a data file conversion library and CLI tool.
//!
//! This crate provides functions to convert between CSV and JSON formats.
//! It is designed to be small, fast, and portable, suitable for use on
//! low-end devices such as Android phones. The core idea is simple: take
//! data in one format, understand its structure, and emit it in another
//! format without unnecessary overhead.
//!
//! # Examples
//!
//! Convert CSV to JSON:
//!
//! ```
//! use sheeter_engine::csv_to_json;
//!
//! let csv = "name,age\nAlice,30\nBob,25";
//! let json = csv_to_json(csv).unwrap();
//! assert_eq!(json, r#"[{"name":"Alice","age":"30"},{"name":"Bob","age":"25"}]"#);
//! ```
//!
//! Convert JSON to CSV:
//!
//! ```
//! use sheeter_engine::json_to_csv;
//!
//! let json = r#"[{"name":"Alice","age":"30"},{"name":"Bob","age":"25"}]"#;
//! let csv = json_to_csv(json).unwrap();
//! assert_eq!(csv, "name,age\nAlice,30\nBob,25\n");
//! ```

pub mod canonical;
pub use canonical::CanonicalValue;

use std::io::Cursor;

/// Converts a delimited string into a JSON array of objects.
///
/// This is the shared engine behind `csv_to_json` and `tsv_to_json`. The first
/// line is read as the header row; every subsequent line becomes a JSON object
/// mapping header names to string cell values. Duplicate header names are
/// rejected because they would silently overwrite data.
///
/// # Errors
///
/// Returns an error on malformed input, duplicate headers, or JSON
/// serialization failure.
///
/// # Examples
///
/// ```
/// use sheeter_engine::csv_to_json;
///
/// let csv = "name,age\nAlice,30";
/// assert_eq!(
///     csv_to_json(csv).unwrap(),
///     r#"[{"name":"Alice","age":"30"}]"#
/// );
/// ```
fn delimited_to_json(input: &str, delim: u8) -> Result<String, Box<dyn std::error::Error>> {
    let input = strip_bom(input);
    let mut rdr = csv::ReaderBuilder::new()
        .delimiter(delim)
        .from_reader(Cursor::new(input));
    let headers = rdr.headers()?.clone();
    let mut seen = std::collections::HashSet::new();
    for header in headers.iter() {
        if !seen.insert(header) {
            return Err(format!("duplicate header: {header}").into());
        }
    }
    let mut records = Vec::new();
    for result in rdr.records() {
        let record = result?;
        let mut map = serde_json::Map::new();
        for (header, value) in headers.iter().zip(record.iter()) {
            map.insert(
                header.to_string(),
                serde_json::Value::String(value.to_string()),
            );
        }
        records.push(serde_json::Value::Object(map));
    }
    Ok(serde_json::to_string(&records)?)
}

/// Converts a JSON array of objects into a delimited string.
///
/// This is the shared engine behind `json_to_csv` and `json_to_tsv`. The header
/// row is the union of all keys across all objects, in first-appearance order.
/// Missing keys become empty cells. Strings are written as-is; numbers and
/// booleans use their JSON literal forms; null becomes an empty cell. Nested
/// objects and arrays cannot be represented losslessly in flat output and cause
/// an error.
///
/// # Errors
///
/// Returns an error if the JSON is not an array of objects, contains nested
/// values, or if writing fails.
///
/// # Examples
///
/// ```
/// use sheeter_engine::json_to_csv;
///
/// let json = r#"[{"a":1},{"a":2,"b":3}]"#;
/// assert_eq!(json_to_csv(json).unwrap(), "a,b\n1,\n2,3\n");
/// ```
fn json_to_delimited(input: &str, delim: u8) -> Result<String, Box<dyn std::error::Error>> {
    let values: Vec<serde_json::Value> = serde_json::from_str(input)?;
    if values.is_empty() {
        return Ok(String::new());
    }
    let mut headers: Vec<String> = Vec::new();
    for value in &values {
        let obj = value.as_object().ok_or("JSON array must contain objects")?;
        for key in obj.keys() {
            if !headers.contains(key) {
                headers.push(key.clone());
            }
        }
    }
    let mut wtr = csv::WriterBuilder::new()
        .delimiter(delim)
        .from_writer(vec![]);
    wtr.write_record(&headers)?;
    for value in values {
        let obj = value.as_object().ok_or("JSON array must contain objects")?;
        let mut record: Vec<String> = Vec::with_capacity(headers.len());
        for h in &headers {
            let cell = match obj.get(h) {
                Some(serde_json::Value::String(s)) => s.clone(),
                Some(serde_json::Value::Number(n)) => n.to_string(),
                Some(serde_json::Value::Bool(b)) => b.to_string(),
                Some(serde_json::Value::Null) => String::new(),
                Some(serde_json::Value::Object(_)) | Some(serde_json::Value::Array(_)) => {
                    return Err(format!(
                        "nested value at key {h} cannot be represented in flat output"
                    )
                    .into());
                }
                None => String::new(),
            };
            record.push(cell);
        }
        wtr.write_record(&record)?;
    }
    let data = wtr.into_inner()?;
    Ok(String::from_utf8(data)?)
}

/// Converts a CSV string into a JSON array of objects.
///
/// CSV (Comma-Separated Values) is a simple tabular format. This function reads
/// the first row as the header and each subsequent row as a record, producing a
/// JSON array of objects. All values are emitted as JSON strings.
///
/// # Errors
///
/// Returns an error on malformed CSV, duplicate headers, or JSON failure.
///
/// # Examples
///
/// ```
/// use sheeter_engine::csv_to_json;
///
/// let csv = "name,age\nAlice,30\nBob,25";
/// let json = csv_to_json(csv).unwrap();
/// assert_eq!(json, r#"[{"name":"Alice","age":"30"},{"name":"Bob","age":"25"}]"#);
/// ```
pub fn csv_to_json(csv: &str) -> Result<String, Box<dyn std::error::Error>> {
    delimited_to_json(csv, b',')
}

/// Converts a TSV string into a JSON array of objects.
///
/// TSV (Tab-Separated Values) is the same tabular model as CSV but uses a tab
/// character as the field separator. This is useful for data exported from
/// spreadsheet tools that prefer tabs over commas.
///
/// # Errors
///
/// Returns an error on malformed TSV, duplicate headers, or JSON failure.
///
/// # Examples
///
/// ```
/// use sheeter_engine::tsv_to_json;
///
/// let tsv = "name\tage\nAlice\t30";
/// let json = tsv_to_json(tsv).unwrap();
/// assert_eq!(json, r#"[{"name":"Alice","age":"30"}]"#);
/// ```
pub fn tsv_to_json(tsv: &str) -> Result<String, Box<dyn std::error::Error>> {
    delimited_to_json(tsv, b'\t')
}

/// Converts a JSON array of objects into a CSV string.
///
/// The header row is the union of all keys across all objects. Missing keys
/// become empty cells. Nested objects or arrays cause an error to prevent
/// silent corruption of round-trips.
///
/// # Errors
///
/// Returns an error if the input is not an array of objects, contains nested
/// values, or if writing fails.
///
/// # Examples
///
/// ```
/// use sheeter_engine::json_to_csv;
///
/// let json = r#"[{"name":"Alice","age":"30"},{"name":"Bob","age":"25"}]"#;
/// assert_eq!(json_to_csv(json).unwrap(), "name,age\nAlice,30\nBob,25\n");
/// ```
pub fn json_to_csv(json: &str) -> Result<String, Box<dyn std::error::Error>> {
    json_to_delimited(json, b',')
}

/// Converts a JSON array of objects into a TSV string.
///
/// Same semantics as `json_to_csv`, but fields are separated by a tab
/// character. The output uses `\n` line endings.
///
/// # Errors
///
/// Returns an error if the input is not an array of objects, contains nested
/// values, or if writing fails.
///
/// # Examples
///
/// ```
/// use sheeter_engine::json_to_tsv;
///
/// let json = r#"[{"name":"Alice","age":"30"},{"name":"Bob","age":"25"}]"#;
/// assert_eq!(json_to_tsv(json).unwrap(), "name\tage\nAlice\t30\nBob\t25\n");
/// ```
pub fn json_to_tsv(json: &str) -> Result<String, Box<dyn std::error::Error>> {
    json_to_delimited(json, b'\t')
}

/// Removes the UTF-8 BOM (`\u{feff}`) from the start of a string if present.
///
/// Some tools (notably Excel) prepend a BOM to CSV/TSV exports. Without
/// stripping, the first header name would include the invisible BOM character
/// and any downstream lookup by name would silently fail. This explicit
/// preprocessing guarantees clean headers regardless of parser behavior.
fn strip_bom(input: &str) -> &str {
    input.strip_prefix('\u{feff}').unwrap_or(input)
}

/// Converts a YAML sequence of mappings into a JSON array of objects.
///
/// Non-string YAML keys (e.g. `1:`) are converted to their string form
/// (`"1"`), matching the convention of every mainstream YAML-to-JSON
/// converter. Collisions are not detected; if the source YAML contains both
/// `1:` and `"1":`, one value wins.
///
/// This function parses YAML with a strict schema to avoid the "Norway problem":
/// `yes`, `no`, `on`, `off`, `y`, `n` are treated as strings under YAML 1.2
/// semantics. Nested sequences or mappings cause an error because they cannot
/// round-trip losslessly through flat CSV/TSV.
///
/// # Errors
///
/// Returns an error if the YAML is not a sequence of mappings, contains nested
/// values, or if JSON serialization fails.
///
/// # Examples
///
/// ```
/// use sheeter_engine::yaml_to_json;
///
/// let yaml = "- name: Alice\n  age: '30'\n- name: Bob\n  age: '25'\n";
/// let json = yaml_to_json(yaml).unwrap();
/// assert_eq!(json, r#"[{"name":"Alice","age":"30"},{"name":"Bob","age":"25"}]"#);
/// ```
pub fn yaml_to_json(yaml: &str) -> Result<String, Box<dyn std::error::Error>> {
    let opts = serde_saphyr::options! {
        strict_booleans: true,
        ignore_binary_tag_for_string: true,
    };
    let values: Vec<serde_json::Value> = serde_saphyr::from_str_with_options(yaml, opts)?;
    for value in &values {
        let obj = value
            .as_object()
            .ok_or("YAML sequence must contain mappings")?;
        for (key, val) in obj {
            if val.is_object() || val.is_array() {
                return Err(format!(
                    "nested YAML value at key {key} cannot be represented in flat output"
                )
                .into());
            }
        }
    }
    Ok(serde_json::to_string(&values)?)
}

/// Converts a JSON array of objects into a YAML sequence of mappings.
///
/// This is the inverse of `yaml_to_json`. The output is a YAML 1.2 document
/// where each object becomes a mapping in a sequence. Key order is preserved.
/// Nested objects or arrays cause an error for the same reason as CSV: they
/// cannot round-trip losslessly through a flat format.
///
/// # Errors
///
/// Returns an error if the JSON is not an array of objects, contains nested
/// values, or if YAML serialization fails.
///
/// # Examples
///
/// ```
/// use sheeter_engine::json_to_yaml;
///
/// let json = r#"[{"name":"Alice","age":"30"}]"#;
/// let yaml = json_to_yaml(json).unwrap();
/// assert!(yaml.contains("name: Alice"));
/// ```
pub fn json_to_yaml(json: &str) -> Result<String, Box<dyn std::error::Error>> {
    let values: Vec<serde_json::Value> = serde_json::from_str(json)?;
    for value in &values {
        let obj = value.as_object().ok_or("JSON array must contain objects")?;
        for (key, val) in obj {
            if val.is_object() || val.is_array() {
                return Err(format!(
                    "nested JSON value at key {key} cannot be represented in flat YAML"
                )
                .into());
            }
        }
    }
    Ok(serde_saphyr::to_string(&values)?)
}

/// Converts CSV to YAML by composing `csv_to_json` and `json_to_yaml`.
///
/// # Examples
///
/// ```
/// use sheeter_engine::csv_to_yaml;
///
/// let csv = "name,age\nAlice,30";
/// let yaml = csv_to_yaml(csv).unwrap();
/// assert!(yaml.contains("name: Alice"));
/// ```
pub fn csv_to_yaml(csv: &str) -> Result<String, Box<dyn std::error::Error>> {
    json_to_yaml(&csv_to_json(csv)?)
}

/// Converts TSV to YAML by composing `tsv_to_json` and `json_to_yaml`.
///
/// # Examples
///
/// ```
/// use sheeter_engine::tsv_to_yaml;
///
/// let tsv = "name\tage\nAlice\t30";
/// let yaml = tsv_to_yaml(tsv).unwrap();
/// assert!(yaml.contains("name: Alice"));
/// ```
pub fn tsv_to_yaml(tsv: &str) -> Result<String, Box<dyn std::error::Error>> {
    json_to_yaml(&tsv_to_json(tsv)?)
}

/// Converts YAML to CSV by composing `yaml_to_json` and `json_to_csv`.
///
/// # Examples
///
/// ```
/// use sheeter_engine::yaml_to_csv;
///
/// let yaml = "- name: Alice\n  age: '30'\n";
/// let csv = yaml_to_csv(yaml).unwrap();
/// assert_eq!(csv, "name,age\nAlice,30\n");
/// ```
pub fn yaml_to_csv(yaml: &str) -> Result<String, Box<dyn std::error::Error>> {
    json_to_csv(&yaml_to_json(yaml)?)
}

/// Converts YAML to TSV by composing `yaml_to_json` and `json_to_tsv`.
///
/// # Examples
///
/// ```
/// use sheeter_engine::yaml_to_tsv;
///
/// let yaml = "- name: Alice\n  age: '30'\n";
/// let tsv = yaml_to_tsv(yaml).unwrap();
/// assert_eq!(tsv, "name\tage\nAlice\t30\n");
/// ```
pub fn yaml_to_tsv(yaml: &str) -> Result<String, Box<dyn std::error::Error>> {
    json_to_tsv(&yaml_to_json(yaml)?)
}

/// Converts CSV to TSV by composing `csv_to_json` and `json_to_tsv`.
///
/// # Examples
///
/// ```
/// use sheeter_engine::csv_to_tsv;
///
/// let csv = "name,age\nAlice,30";
/// let tsv = csv_to_tsv(csv).unwrap();
/// assert_eq!(tsv, "name\tage\nAlice\t30\n");
/// ```
pub fn csv_to_tsv(csv: &str) -> Result<String, Box<dyn std::error::Error>> {
    json_to_tsv(&csv_to_json(csv)?)
}

/// Converts TSV to CSV by composing `tsv_to_json` and `json_to_csv`.
///
/// # Examples
///
/// ```
/// use sheeter_engine::tsv_to_csv;
///
/// let tsv = "name\tage\nAlice\t30";
/// let csv = tsv_to_csv(tsv).unwrap();
/// assert_eq!(csv, "name,age\nAlice,30\n");
/// ```
pub fn tsv_to_csv(tsv: &str) -> Result<String, Box<dyn std::error::Error>> {
    json_to_csv(&tsv_to_json(tsv)?)
}

/// Converts an XML document to a JSON representation.
///
/// Attributes become `@name` keys, text becomes `#text`, and repeated
/// sibling elements become arrays. The output has exactly one top-level key:
/// the root element name.
///
/// # Errors
/// Returns an error if the XML is malformed or empty.
///
/// # Examples
/// ```
/// use sheeter_engine::xml_to_json;
/// let json = xml_to_json("<r><a>1</a><a>2</a></r>").unwrap();
/// assert_eq!(json, r#"{"r":{"a":["1","2"]}}"#);
/// ```
pub fn xml_to_json(xml: &str) -> Result<String, Box<dyn std::error::Error>> {
    CanonicalValue::from_xml(xml)?.to_json()
}

/// Converts a JSON value to XML.
///
/// Tabular JSON (array of objects) is wrapped in `<root><item>...`. Other
/// JSON shapes are wrapped in `<root>` unless they are a single-key object,
/// which becomes the root element directly. Keys starting with `@` become
/// attributes and `#text` becomes text content.
///
/// # Errors
/// Returns an error if the JSON is malformed.
///
/// # Examples
/// ```
/// use sheeter_engine::json_to_xml;
/// let xml = json_to_xml(r#"[{"a":"1"}]"#).unwrap();
/// assert!(xml.contains("<root>"));
/// ```
pub fn json_to_xml(json: &str) -> Result<String, Box<dyn std::error::Error>> {
    CanonicalValue::from_json(json)?.to_xml()
}

/// Converts CSV to XML via the canonical hub.
///
/// # Examples
/// ```
/// use sheeter_engine::csv_to_xml;
/// let xml = csv_to_xml("a\n1").unwrap();
/// assert!(xml.contains("<item>"));
/// ```
pub fn csv_to_xml(input: &str) -> Result<String, Box<dyn std::error::Error>> {
    CanonicalValue::from_csv(input)?.to_xml()
}

/// Converts TSV to XML via the canonical hub.
///
/// # Examples
/// ```
/// use sheeter_engine::tsv_to_xml;
/// let xml = tsv_to_xml("a\tb\n1\t2").unwrap();
/// assert!(xml.contains("<item>"));
/// ```
pub fn tsv_to_xml(input: &str) -> Result<String, Box<dyn std::error::Error>> {
    CanonicalValue::from_tsv(input)?.to_xml()
}

/// Converts YAML to XML via the canonical hub.
///
/// # Examples
/// ```
/// use sheeter_engine::yaml_to_xml;
/// let xml = yaml_to_xml("- a: 1\n").unwrap();
/// assert!(xml.contains("<item>"));
/// ```
pub fn yaml_to_xml(input: &str) -> Result<String, Box<dyn std::error::Error>> {
    CanonicalValue::from_yaml(input)?.to_xml()
}

/// Converts XML to CSV, extracting the tabular array if present.
///
/// Expects the XML to follow `<root><item><col>value</col></item></root>`
/// (or any single-level root whose single child key holds the rows). Errors
/// if the structure is not tabular.
///
/// # Errors
/// Returns an error if the XML is malformed or not tabular.
///
/// # Examples
/// ```
/// use sheeter_engine::xml_to_csv;
/// let csv = xml_to_csv("<root><item><a>1</a></item></root>").unwrap();
/// assert_eq!(csv, "a\n1\n");
/// ```
pub fn xml_to_csv(xml: &str) -> Result<String, Box<dyn std::error::Error>> {
    CanonicalValue::from_xml(xml)?.to_csv()
}

/// Converts XML to TSV, extracting the tabular array if present.
///
/// # Examples
/// ```
/// use sheeter_engine::xml_to_tsv;
/// let tsv = xml_to_tsv("<root><item><a>1</a></item></root>").unwrap();
/// assert_eq!(tsv, "a\n1\n");
/// ```
pub fn xml_to_tsv(xml: &str) -> Result<String, Box<dyn std::error::Error>> {
    CanonicalValue::from_xml(xml)?.to_tsv()
}

/// Converts XML to YAML, extracting the tabular array if present.
///
/// # Examples
/// ```
/// use sheeter_engine::xml_to_yaml;
/// let yaml = xml_to_yaml("<root><item><a>1</a></item></root>").unwrap();
/// assert!(yaml.contains("a:"));
/// ```
pub fn xml_to_yaml(xml: &str) -> Result<String, Box<dyn std::error::Error>> {
    CanonicalValue::from_xml(xml)?.to_yaml()
}

/// Converts a TOML document to a JSON value.
///
/// TOML datetimes are stringified (`2024-01-15T10:30:00Z` becomes the string
/// `"2024-01-15T10:30:00Z"`), matching the behavior of YAML. Nested tables
/// and arrays of tables map directly to JSON objects and arrays.
///
/// # Errors
/// Returns an error if the TOML is malformed.
///
/// # Examples
/// ```
/// use sheeter_engine::toml_to_json;
/// let json = toml_to_json("a = 1\n").unwrap();
/// assert_eq!(json, r#"{"a":1}"#);
/// ```
pub fn toml_to_json(toml: &str) -> Result<String, Box<dyn std::error::Error>> {
    CanonicalValue::from_toml(toml)?.to_json()
}

/// Converts a TOML document to CSV, extracting the first array of tables.
///
/// Flat TOML documents (all scalar values) become a single-row CSV. Documents
/// with an array of tables at any depth use that array as the row source.
///
/// # Errors
/// Returns an error if the TOML is malformed or has no tabular structure.
///
/// # Examples
/// ```
/// use sheeter_engine::toml_to_csv;
/// assert_eq!(toml_to_csv("a = 1\n").unwrap(), "a\n1\n");
/// ```
pub fn toml_to_csv(toml: &str) -> Result<String, Box<dyn std::error::Error>> {
    CanonicalValue::from_toml(toml)?.to_csv()
}

/// Converts a TOML document to TSV.
///
/// # Errors
/// Returns an error if the TOML is malformed or has no tabular structure.
///
/// # Examples
/// ```
/// use sheeter_engine::toml_to_tsv;
/// assert_eq!(toml_to_tsv("a = 1\n").unwrap(), "a\n1\n");
/// ```
pub fn toml_to_tsv(toml: &str) -> Result<String, Box<dyn std::error::Error>> {
    CanonicalValue::from_toml(toml)?.to_tsv()
}

/// Converts a TOML document to YAML.
///
/// # Errors
/// Returns an error if the TOML is malformed.
///
/// # Examples
/// ```
/// use sheeter_engine::toml_to_yaml;
/// let yaml = toml_to_yaml("a = 1\n").unwrap();
/// assert!(yaml.contains("a:"));
/// ```
pub fn toml_to_yaml(toml: &str) -> Result<String, Box<dyn std::error::Error>> {
    CanonicalValue::from_toml(toml)?.to_yaml()
}

/// Converts a TOML document to XML.
///
/// # Errors
/// Returns an error if the TOML is malformed.
///
/// # Examples
/// ```
/// use sheeter_engine::toml_to_xml;
/// let xml = toml_to_xml("a = 1\n").unwrap();
/// assert!(xml.contains("<a>"));
/// ```
pub fn toml_to_xml(toml: &str) -> Result<String, Box<dyn std::error::Error>> {
    CanonicalValue::from_toml(toml)?.to_xml()
}

/// Converts a JSON value to TOML.
///
/// JSON arrays at the root are wrapped in `{item: [...]}` because TOML
/// requires a table at the document root. Null values are skipped, since
/// TOML has no null type; JSON arrays containing null error out.
///
/// # Errors
/// Returns an error if the JSON is malformed or contains values TOML cannot
/// represent (null inside arrays, integers outside i64 range).
///
/// # Examples
/// ```
/// use sheeter_engine::json_to_toml;
/// let toml = json_to_toml(r#"{"a":1}"#).unwrap();
/// assert!(toml.contains("a = 1"));
/// ```
pub fn json_to_toml(json: &str) -> Result<String, Box<dyn std::error::Error>> {
    CanonicalValue::from_json(json)?.to_toml()
}

/// Converts CSV to TOML via the canonical hub.
///
/// The resulting TOML document is `[[item]]` array-of-tables, one item per
/// CSV row.
///
/// # Errors
/// Returns an error if the CSV is malformed.
///
/// # Examples
/// ```
/// use sheeter_engine::csv_to_toml;
/// let toml = csv_to_toml("a\n1\n").unwrap();
/// assert!(toml.contains("[[item]]"));
/// ```
pub fn csv_to_toml(csv: &str) -> Result<String, Box<dyn std::error::Error>> {
    CanonicalValue::from_csv(csv)?.to_toml()
}

/// Converts TSV to TOML via the canonical hub.
///
/// # Errors
/// Returns an error if the TSV is malformed.
///
/// # Examples
/// ```
/// use sheeter_engine::tsv_to_toml;
/// let toml = tsv_to_toml("a\tb\n1\t2\n").unwrap();
/// assert!(toml.contains("[[item]]"));
/// ```
pub fn tsv_to_toml(tsv: &str) -> Result<String, Box<dyn std::error::Error>> {
    CanonicalValue::from_tsv(tsv)?.to_toml()
}

/// Converts YAML to TOML via the canonical hub.
///
/// # Errors
/// Returns an error if the YAML is malformed or cannot be represented in TOML.
///
/// # Examples
/// ```
/// use sheeter_engine::yaml_to_toml;
/// let toml = yaml_to_toml("- a: 1\n").unwrap();
/// assert!(toml.contains("[[item]]"));
/// ```
pub fn yaml_to_toml(yaml: &str) -> Result<String, Box<dyn std::error::Error>> {
    CanonicalValue::from_yaml(yaml)?.to_toml()
}

/// Converts XML to TOML via the canonical hub.
///
/// Attribute markers (`@name`) and text markers (`#text`) are preserved as
/// quoted TOML keys, allowing round-trip back to XML.
///
/// # Errors
/// Returns an error if the XML is malformed or cannot be represented in TOML.
///
/// # Examples
/// ```
/// use sheeter_engine::xml_to_toml;
/// let toml = xml_to_toml("<r><a>1</a></r>").unwrap();
/// assert!(toml.contains("a = \"1\""));
/// ```
pub fn xml_to_toml(xml: &str) -> Result<String, Box<dyn std::error::Error>> {
    CanonicalValue::from_xml(xml)?.to_toml()
}