Skip to main content

agent_first_data/
formatting.rs

1use crate::document::{Value as DocumentValue, non_finite_spelling};
2use crate::output::OutputFormat;
3use crate::redaction::{OutputOptions, PlainStyle, REDACTED_MARKER};
4use serde_json::Value;
5
6/// Render a value as a string in the given format with the given options.
7///
8/// The single `value × format × options → String` entry point. JSON and YAML
9/// are structure-preserving and ignore [`PlainStyle`]; plain honors it. All
10/// three redact through `options.redaction` before rendering.
11pub fn render(value: &Value, format: OutputFormat, options: &OutputOptions) -> String {
12    match format {
13        OutputFormat::Json => serialize_json_output(&options.redaction.value(value)),
14        OutputFormat::Yaml => render_yaml(value, options),
15        OutputFormat::Plain => render_plain(value, options),
16    }
17}
18
19pub(crate) fn serialize_json_output(value: &Value) -> String {
20    match serde_json::to_string(value) {
21        Ok(s) => s,
22        Err(err) => serde_json::json!({
23            "error": "output_json_failed",
24            "detail": err.to_string(),
25        })
26        .to_string(),
27    }
28}
29
30/// Format as multi-line YAML with the given output options.
31///
32/// YAML output ignores [`PlainStyle`] and always preserves original keys and values after
33/// redaction, the same structure-preserving semantics as JSON.
34pub(crate) fn render_yaml(value: &Value, output_options: &OutputOptions) -> String {
35    render_yaml_value(&output_options.redaction.value(value), None)
36}
37
38pub(crate) fn render_yaml_value(value: &Value, original: Option<&DocumentValue>) -> String {
39    let mut lines = vec!["---".to_string()];
40    render_yaml_raw(value, original, 0, &mut lines);
41    lines.join("\n")
42}
43
44/// Format as single-line logfmt with the given output options.
45pub(crate) fn render_plain(value: &Value, output_options: &OutputOptions) -> String {
46    let mut pairs: Vec<(String, String)> = Vec::new();
47    let v = output_options.redaction.value(value);
48    if !v.is_object() {
49        return escape_plain_text(&plain_scalar(&v), false);
50    }
51    match output_options.style {
52        PlainStyle::Readable => collect_plain_pairs(&v, "", &mut pairs),
53        PlainStyle::Raw => collect_plain_pairs_raw(&v, "", &mut pairs),
54    }
55    if pairs.is_empty() {
56        return "{}".to_string();
57    }
58    pairs.sort_by(|(a, _), (b, _)| a.encode_utf16().cmp(b.encode_utf16()));
59    pairs
60        .into_iter()
61        .map(|(k, v)| format!("{}={}", quote_logfmt_key(&k), quote_logfmt_value(&v)))
62        .collect::<Vec<_>>()
63        .join(" ")
64}
65
66// ═══════════════════════════════════════════
67// Suffix Processing
68// ═══════════════════════════════════════════
69
70fn strip_suffix_ci(key: &str, suffix_lower: &str) -> Option<String> {
71    crate::suffix::strip_suffix(key, suffix_lower).map(str::to_owned)
72}
73
74/// Extract currency code from `_{code}_cents` / `_{CODE}_CENTS` pattern.
75fn try_strip_generic_cents(key: &str) -> Option<(String, String)> {
76    let code = extract_currency_code(key)?;
77    let suffix_len = code.len() + "_cents".len() + 1; // _{code}_cents
78    let stripped = &key[..key.len() - suffix_len];
79    if stripped.is_empty() {
80        return None;
81    }
82    Some((stripped.to_string(), code.to_string()))
83}
84
85/// Extract currency code from `_{code}_micro` / `_{CODE}_MICRO` pattern.
86fn try_strip_generic_micro(key: &str) -> Option<(String, String)> {
87    let code = crate::suffix::currency_code(key, "_micro")?;
88    let suffix_len = code.len() + "_micro".len() + 1; // _{code}_micro
89    let stripped = &key[..key.len() - suffix_len];
90    if stripped.is_empty() {
91        return None;
92    }
93    Some((stripped.to_string(), code.to_string()))
94}
95
96/// Accept an integer value, including an integral-valued float (`3.0` → `3`).
97/// Non-integral floats and out-of-range values return `None`. This keeps the
98/// four language implementations consistent: JS/TS cannot distinguish `3` from
99/// `3.0` after JSON parsing, so the value's integrality — not its lexical form —
100/// decides whether an integer-required suffix applies.
101fn as_int(value: &Value) -> Option<i64> {
102    if let Some(i) = value.as_i64() {
103        return Some(i);
104    }
105    if value.is_u64() {
106        return value.as_u64()?.try_into().ok();
107    }
108    // An integer literal that neither `as_i64` nor `as_u64` accepted is out of
109    // i64 range. Converting `i64::MIN - 1` through f64 would round it back into
110    // range, formatting a plausible but wrong amount on a money field. The
111    // positive side is already refused by the `is_u64` check above. Floating
112    // literals below are also checked on their exact decimal digits.
113    if let Value::Number(number) = value
114        && number_is_integer_literal(number)
115    {
116        return None;
117    }
118    let Value::Number(number) = value else {
119        return None;
120    };
121    integral_float_text(&number.to_string())?.parse().ok()
122}
123
124/// Whether the producer wrote this number as an integer literal.
125///
126/// Shared with the linter: both need to tell "the author wrote an integer" from
127/// "the value happens to be integral", and they must not answer it differently.
128pub(crate) fn number_is_integer_literal(number: &serde_json::Number) -> bool {
129    !number.to_string().contains(['.', 'e', 'E'])
130}
131
132/// Like [`as_int`] but for non-negative integers (rejects negatives).
133fn as_uint(value: &Value) -> Option<u64> {
134    if let Some(u) = value.as_u64() {
135        return Some(u);
136    }
137    if value.as_i64() == Some(0) {
138        return Some(0);
139    }
140    if let Value::Number(number) = value
141        && number_is_integer_literal(number)
142    {
143        return None;
144    }
145    let Value::Number(number) = value else {
146        return None;
147    };
148    let integer = integral_float_text(&number.to_string())?;
149    if integer == "-0" {
150        return Some(0);
151    }
152    integer.parse().ok()
153}
154
155/// The exact digits of an integer-valued number or decimal integer string, of
156/// any magnitude. Bitcoin amounts and `_epoch_ns` only append a unit or
157/// divide, so unlike money suffixes they are not bounded by `i64`: an integer
158/// literal keeps its digits, and a float literal counts when its value is an
159/// integer below 1e21 (the canonical number form's integer range). A numeric
160/// `-0` is zero.
161fn integer_text(value: &Value) -> Option<String> {
162    match value {
163        Value::Number(number) => {
164            let literal = number.to_string();
165            let integer = if number_is_integer_literal(number) {
166                literal
167            } else {
168                integral_float_text(&literal)?
169            };
170            Some(if integer == "-0" { "0".into() } else { integer })
171        }
172        Value::String(s) if is_decimal_integer_string(s) => Some(s.clone()),
173        _ => None,
174    }
175}
176
177fn is_decimal_integer_string(s: &str) -> bool {
178    let digits = s.trim_prefix('-');
179    !digits.is_empty() && digits.bytes().all(|b| b.is_ascii_digit())
180}
181
182/// Floor-divide an integer nanosecond count of any size to milliseconds.
183/// `i128` spans ±1.7e38 ns, far beyond the RFC 3339 year range, so a count it
184/// cannot hold is out of range for the same reason a smaller one can be.
185fn epoch_ns_to_ms(value: &Value) -> Option<i64> {
186    let ns = integer_text(value)?.parse::<i128>().ok()?;
187    ns.div_euclid(1_000_000).try_into().ok()
188}
189
190/// Try suffix-driven processing. Returns `Some((stripped_key, formatted_value))`
191/// when the suffix matches and the type is valid; `None` for no match or a type
192/// mismatch.
193fn try_process_field(key: &str, value: &Value) -> Option<(String, String)> {
194    // Group 1: compound timestamp suffixes
195    if let Some(stripped) = strip_suffix_ci(key, "_epoch_ms") {
196        return as_int(value)
197            .and_then(|ms| format_rfc3339_ms(ms).map(|formatted| (stripped, formatted)));
198    }
199    if let Some(stripped) = strip_suffix_ci(key, "_epoch_s") {
200        return as_int(value)
201            .and_then(|s| s.checked_mul(1000))
202            .and_then(|ms| format_rfc3339_ms(ms).map(|formatted| (stripped, formatted)));
203    }
204    if let Some(stripped) = strip_suffix_ci(key, "_epoch_ns") {
205        return epoch_ns_to_ms(value)
206            .and_then(|ms| format_rfc3339_ms(ms).map(|formatted| (stripped, formatted)));
207    }
208
209    // Group 2: compound currency suffixes
210    if let Some(stripped) = strip_suffix_ci(key, "_usd_cents") {
211        return as_int(value).map(|n| {
212            let (sign, magnitude) = signed_magnitude(n);
213            (
214                stripped,
215                format!("{sign}${}.{:02}", magnitude / 100, magnitude % 100),
216            )
217        });
218    }
219    if let Some(stripped) = strip_suffix_ci(key, "_eur_cents") {
220        return as_int(value).map(|n| {
221            let (sign, magnitude) = signed_magnitude(n);
222            (
223                stripped,
224                format!("{sign}€{}.{:02}", magnitude / 100, magnitude % 100),
225            )
226        });
227    }
228    if let Some((stripped, code)) = try_strip_generic_cents(key) {
229        return as_int(value).map(|n| {
230            let (sign, magnitude) = signed_magnitude(n);
231            (
232                stripped,
233                format!(
234                    "{sign}{}.{:02} {}",
235                    magnitude / 100,
236                    magnitude % 100,
237                    code.to_uppercase()
238                ),
239            )
240        });
241    }
242    if let Some((stripped, code)) = try_strip_generic_micro(key) {
243        return as_int(value).map(|n| {
244            let (sign, magnitude) = signed_magnitude(n);
245            (
246                stripped,
247                format!(
248                    "{sign}{}.{:06} {}",
249                    magnitude / 1_000_000,
250                    magnitude % 1_000_000,
251                    code.to_uppercase()
252                ),
253            )
254        });
255    }
256
257    // Group 3: multi-char suffixes
258    if let Some(stripped) = strip_suffix_ci(key, "_rfc3339") {
259        return value.as_str().map(|s| (stripped, s.to_string()));
260    }
261    if let Some(stripped) = strip_suffix_ci(key, "_minutes") {
262        return value
263            .is_number()
264            .then(|| (stripped, format!("{} minutes", number_str(value))));
265    }
266    if let Some(stripped) = strip_suffix_ci(key, "_hours") {
267        return value
268            .is_number()
269            .then(|| (stripped, format!("{} hours", number_str(value))));
270    }
271    if let Some(stripped) = strip_suffix_ci(key, "_days") {
272        return value
273            .is_number()
274            .then(|| (stripped, format!("{} days", number_str(value))));
275    }
276
277    // Group 4: single-unit suffixes
278    if let Some(stripped) = strip_suffix_ci(key, "_msats") {
279        return integer_text(value).map(|n| (stripped, format!("{n}msats")));
280    }
281    if let Some(stripped) = strip_suffix_ci(key, "_sats") {
282        return integer_text(value).map(|n| (stripped, format!("{n}sats")));
283    }
284    if let Some(stripped) = strip_suffix_ci(key, "_bytes") {
285        return as_uint(value).map(|n| (stripped, format_bytes_human(n)));
286    }
287    if let Some(stripped) = strip_suffix_ci(key, "_percent") {
288        return value
289            .is_number()
290            .then(|| (stripped, format!("{}%", number_str(value))));
291    }
292    // Group 5: short suffixes (last to avoid false positives)
293    if let Some(stripped) = strip_suffix_ci(key, "_jpy") {
294        return as_int(value).map(|n| {
295            let (sign, magnitude) = signed_magnitude(n);
296            (
297                stripped,
298                format!("{sign}¥{}", format_with_commas(magnitude)),
299            )
300        });
301    }
302    if let Some(stripped) = strip_suffix_ci(key, "_ns") {
303        return value
304            .is_number()
305            .then(|| (stripped, format!("{}ns", number_str(value))));
306    }
307    if let Some(stripped) = strip_suffix_ci(key, "_us") {
308        return value
309            .is_number()
310            .then(|| (stripped, format!("{}μs", number_str(value))));
311    }
312    if let Some(stripped) = strip_suffix_ci(key, "_ms") {
313        return format_ms_value(value).map(|v| (stripped, v));
314    }
315    if let Some(stripped) = strip_suffix_ci(key, "_s") {
316        return value
317            .is_number()
318            .then(|| (stripped, format!("{}s", number_str(value))));
319    }
320
321    None
322}
323
324/// True when a field already carries the redaction marker, i.e. redaction ran
325/// over it and hid the value.
326fn is_redacted(value: &Value) -> bool {
327    value.as_str() == Some(REDACTED_MARKER)
328}
329
330/// Process object fields: strip keys, format values, detect collisions.
331fn process_object_fields<'a>(
332    map: &'a serde_json::Map<String, Value>,
333) -> Vec<(String, &'a Value, Option<String>)> {
334    let mut entries: Vec<(String, &'a str, &'a Value, Option<String>)> = Vec::new();
335    for (key, value) in map {
336        if let Some(stripped) = strip_suffix_ci(key, "_secret") {
337            // Dropping `_secret` is the readable half of an actual redaction: the
338            // marker has done its job once the value reads `***`. When the value
339            // was *not* redacted — policy `Off`, or a field outside `trace` under
340            // `TraceOnly` — the suffix is the only thing telling a downstream
341            // reader that `api_key_secret=sk-live-xxx` is a credential, so it
342            // stays.
343            let display_key = if is_redacted(value) {
344                stripped
345            } else {
346                key.clone()
347            };
348            entries.push((display_key, key.as_str(), value, None));
349            continue;
350        }
351        match try_process_field(key, value) {
352            Some((stripped, formatted)) => {
353                entries.push((stripped, key.as_str(), value, Some(formatted)));
354            }
355            None => {
356                entries.push((key.clone(), key.as_str(), value, None));
357            }
358        }
359    }
360
361    // Detect collisions
362    let mut counts: std::collections::HashMap<String, usize> = std::collections::HashMap::new();
363    for (stripped, _, _, _) in &entries {
364        *counts.entry(stripped.clone()).or_insert(0) += 1;
365    }
366
367    // Resolve collisions: revert both key and formatted value
368    let mut result: Vec<(String, &'a Value, Option<String>)> = entries
369        .into_iter()
370        .map(|(stripped, original, value, formatted)| {
371            if counts.get(&stripped).copied().unwrap_or(0) > 1 && original != stripped.as_str() {
372                (original.to_string(), value, None)
373            } else {
374                (stripped, value, formatted)
375            }
376        })
377        .collect();
378
379    result.sort_by(|(a, _, _), (b, _, _)| a.encode_utf16().cmp(b.encode_utf16()));
380    result
381}
382
383// ═══════════════════════════════════════════
384// Formatting Helpers
385// ═══════════════════════════════════════════
386
387fn number_str(value: &Value) -> String {
388    match value {
389        Value::Number(n) => format_number(n),
390        _ => String::new(),
391    }
392}
393
394/// Render a JSON number canonically for YAML/plain output: a float literal
395/// whose value is an integer below 1e21 in magnitude renders as that integer
396/// (`3.0` → `3`, `-0.0` → `-0`, `1.5e2` → `150`); everything else keeps its
397/// digits, placed by [`place_decimal_point`]. Go, Python and TypeScript apply
398/// the same rule to native floats and to decoded literals alike, so the four
399/// implementations stay byte-identical.
400///
401/// Decided on the literal's text rather than through `f64`, which would round
402/// `9007199254740993.0` to `…992`: rendering may change a number's spelling,
403/// never its digits.
404fn format_number(n: &serde_json::Number) -> String {
405    let literal = n.to_string();
406    integral_float_text(&literal)
407        .or_else(|| place_decimal_point(&literal))
408        .unwrap_or_else(|| normalize_exponent(&literal))
409}
410
411/// Spell a non-integral float literal with the notation ECMAScript's
412/// `Number#toString` picks: positional when the value lies in [1e-6, 1e21),
413/// exponent form otherwise. Each runtime's native formatter switches at a
414/// different magnitude (ryu below 1e-5, Python and Go below 1e-4, Go also from
415/// 1e6), so the choice is made here, on the digits as written. `None` for
416/// integer literals and exponents beyond `i64`, which keep their spelling.
417fn place_decimal_point(literal: &str) -> Option<String> {
418    if !literal.contains(['.', 'e', 'E']) {
419        return None;
420    }
421    let (sign, unsigned) = match literal.strip_prefix('-') {
422        Some(rest) => ("-", rest),
423        None => ("", literal),
424    };
425    let (mantissa, exponent) = match unsigned.find(['e', 'E']) {
426        Some(index) => (&unsigned[..index], &unsigned[index + 1..]),
427        None => (unsigned, "0"),
428    };
429    let (whole, fraction) = mantissa.split_once('.').unwrap_or((mantissa, ""));
430    let digits = format!("{whole}{fraction}");
431    let leading = digits.bytes().take_while(|digit| *digit == b'0').count();
432    let significant = &digits[leading..];
433    if significant.is_empty() {
434        return None;
435    }
436    // `point`: how many significant digits precede the decimal point.
437    let point = i64::try_from(whole.len())
438        .ok()?
439        .checked_sub(i64::try_from(leading).ok()?)?
440        .checked_add(exponent.parse::<i64>().ok()?)?;
441    let text = if (1..=21).contains(&point) {
442        let split = usize::try_from(point).ok()?.min(significant.len());
443        let (integer, rest) = significant.split_at(split);
444        if rest.is_empty() {
445            // An integral value at or beyond the point is integral_float_text's.
446            return None;
447        }
448        format!("{integer}.{rest}")
449    } else if (-5..=0).contains(&point) {
450        let zeros = "0".repeat(usize::try_from(-point).ok()?);
451        format!("0.{zeros}{significant}")
452    } else {
453        let (first, rest) = significant.split_at(1);
454        let scale = point.checked_sub(1)?;
455        let marker = if scale < 0 { "-" } else { "+" };
456        let rest = if rest.is_empty() {
457            String::new()
458        } else {
459            format!(".{rest}")
460        };
461        format!("{first}{rest}e{marker}{}", scale.unsigned_abs())
462    };
463    Some(format!("{sign}{text}"))
464}
465
466/// The exact integer a float literal denotes, when it denotes one below 1e21
467/// in magnitude. `None` for integer literals (already canonical), fractional
468/// values, and anything at or beyond 1e21, which keeps exponent form.
469fn integral_float_text(literal: &str) -> Option<String> {
470    if !literal.contains(['.', 'e', 'E']) {
471        return None;
472    }
473    let (negative, unsigned) = match literal.strip_prefix('-') {
474        Some(rest) => (true, rest),
475        None => (false, literal),
476    };
477    let (mantissa, exponent) = match unsigned.find(['e', 'E']) {
478        Some(index) => (&unsigned[..index], &unsigned[index + 1..]),
479        None => (unsigned, "0"),
480    };
481    let (whole, fraction) = mantissa.split_once('.').unwrap_or((mantissa, ""));
482    let digits = format!("{whole}{fraction}");
483    if digits.bytes().all(|digit| digit == b'0') {
484        return Some(if negative { "-0" } else { "0" }.into());
485    }
486    let exponent = exponent.parse::<i64>().ok()?;
487    // Where the decimal point falls in `digits` once the exponent is applied.
488    let point = i64::try_from(whole.len()).ok()?.checked_add(exponent)?;
489    let split = usize::try_from(point.clamp(0, i64::try_from(digits.len()).ok()?)).ok()?;
490    if digits[split..].bytes().any(|digit| digit != b'0') {
491        return None;
492    }
493    let padding = usize::try_from(point)
494        .unwrap_or(0)
495        .saturating_sub(digits.len());
496    let integer = format!("{}{}", &digits[..split], "0".repeat(padding.min(22)));
497    let integer = integer.trim_start_matches('0');
498    if integer.len() > 21 {
499        return None;
500    }
501    let integer = if integer.is_empty() { "0" } else { integer };
502    Some(if negative {
503        format!("-{integer}")
504    } else {
505        integer.to_string()
506    })
507}
508
509fn normalize_exponent(s: &str) -> String {
510    let Some(e) = s.find(['e', 'E']) else {
511        return s.to_string();
512    };
513    let mantissa = &s[..e];
514    let mut exp = &s[e + 1..];
515    // An unsigned exponent is a positive one: spell it `e+` like every
516    // native float formatter, so a decoded literal renders the same.
517    let mut sign = "+";
518    if exp.starts_with(['+', '-']) {
519        sign = &exp[..1];
520        exp = &exp[1..];
521    }
522    let exp = exp.trim_start_matches('0');
523    let exp = if exp.is_empty() { "0" } else { exp };
524    format!("{mantissa}e{sign}{exp}")
525}
526
527/// Format ms as seconds: 3 decimal places, trim trailing zeros, min 1 decimal.
528fn format_ms_as_seconds(ms: f64) -> String {
529    let formatted = format!("{:.3}", ms / 1000.0);
530    let trimmed = formatted.trim_end_matches('0');
531    if trimmed.ends_with('.') {
532        format!("{trimmed}0s")
533    } else {
534        format!("{trimmed}s")
535    }
536}
537
538/// Split a signed integer into its sign text and magnitude.
539///
540/// Taking the magnitude before dividing keeps currency formatting identical
541/// across the four languages: Rust and Go truncate toward zero while Python
542/// floors toward negative infinity, so `-499 / 100` does not agree, but
543/// `-(499 / 100)` does.
544fn signed_magnitude(value: i64) -> (&'static str, u64) {
545    if value < 0 {
546        ("-", value.unsigned_abs())
547    } else {
548        ("", value as u64)
549    }
550}
551
552/// Format `_ms` value: < 1000 → `{n}ms`, >= 1000 → seconds.
553fn format_ms_value(value: &Value) -> Option<String> {
554    // A decoded literal beyond f64 parses as infinity; it cannot be converted
555    // to seconds, so it keeps its raw key and digits as in the other SDKs.
556    let n = value.as_f64().filter(|n| n.is_finite())?;
557    if n.abs() >= 1000.0 {
558        Some(format_ms_as_seconds(n))
559    } else {
560        Some(format!("{}ms", number_str(value)))
561    }
562}
563
564/// Convert unix milliseconds (signed) to RFC 3339 with UTC timezone.
565const MIN_RFC3339_MS: i64 = -62135596800000;
566const MAX_RFC3339_MS: i64 = 253402300799999;
567
568fn format_rfc3339_ms(ms: i64) -> Option<String> {
569    if !(MIN_RFC3339_MS..=MAX_RFC3339_MS).contains(&ms) {
570        return None;
571    }
572    // Civil time rather than jiff::Timestamp: Timestamp stops short of
573    // 9999-12-31 to leave room for UTC offsets, and this range ends there.
574    jiff::civil::date(1970, 1, 1)
575        .at(0, 0, 0, 0)
576        .checked_add(jiff::SignedDuration::from_millis(ms))
577        .ok()
578        .map(|utc| format!("{utc:.3}Z"))
579}
580
581/// Format non-negative bytes as human-readable binary size.
582pub(crate) fn format_bytes_human(bytes: u64) -> String {
583    const KIB: f64 = 1024.0;
584    const MIB: f64 = KIB * 1024.0;
585    const GIB: f64 = MIB * 1024.0;
586    const TIB: f64 = GIB * 1024.0;
587
588    let b = bytes as f64;
589    if b >= TIB {
590        format!("{:.1}TiB", b / TIB)
591    } else if b >= GIB {
592        format!("{:.1}GiB", b / GIB)
593    } else if b >= MIB {
594        format!("{:.1}MiB", b / MIB)
595    } else if b >= KIB {
596        format!("{:.1}KiB", b / KIB)
597    } else {
598        format!("{bytes}B")
599    }
600}
601
602/// Format a number with thousands separators.
603pub(crate) fn format_with_commas(n: u64) -> String {
604    let s = n.to_string();
605    let mut result = String::with_capacity(s.len() + s.len() / 3);
606    for (i, c) in s.chars().enumerate() {
607        if i > 0 && (s.len() - i).is_multiple_of(3) {
608            result.push(',');
609        }
610        result.push(c);
611    }
612    result
613}
614
615/// Extract currency code from a `_{code}_cents` / `_{CODE}_CENTS` suffix.
616pub(crate) fn extract_currency_code(key: &str) -> Option<&str> {
617    crate::suffix::currency_code(key, "_cents")
618}
619
620// ═══════════════════════════════════════════
621// YAML Rendering (structure-preserving)
622// ═══════════════════════════════════════════
623
624fn render_yaml_raw(
625    value: &Value,
626    original: Option<&DocumentValue>,
627    indent: usize,
628    lines: &mut Vec<String>,
629) {
630    let prefix = "  ".repeat(indent);
631    match value {
632        Value::Object(map) => {
633            for key in sorted_value_keys(map) {
634                render_yaml_field_raw(
635                    &prefix,
636                    &key,
637                    &map[&key],
638                    original.and_then(|value| value.get(&key)),
639                    indent,
640                    lines,
641                );
642            }
643        }
644        Value::Array(arr) => {
645            render_yaml_array_raw(arr, original, indent, lines);
646        }
647        _ => {
648            lines.push(format!("{}{}", prefix, yaml_scalar(value, original)));
649        }
650    }
651}
652
653fn render_yaml_field_raw(
654    prefix: &str,
655    key: &str,
656    value: &Value,
657    original: Option<&DocumentValue>,
658    indent: usize,
659    lines: &mut Vec<String>,
660) {
661    match value {
662        Value::Object(inner) if !inner.is_empty() => {
663            lines.push(format!("{}{}:", prefix, yaml_key(key)));
664            render_yaml_raw(value, original, indent + 1, lines);
665        }
666        Value::Object(_) => {
667            lines.push(format!("{}{}: {{}}", prefix, yaml_key(key)));
668        }
669        Value::Array(arr) => {
670            if arr.is_empty() {
671                lines.push(format!("{}{}: []", prefix, yaml_key(key)));
672            } else {
673                lines.push(format!("{}{}:", prefix, yaml_key(key)));
674                render_yaml_array_raw(arr, original, indent + 1, lines);
675            }
676        }
677        _ => {
678            lines.push(format!(
679                "{}{}: {}",
680                prefix,
681                yaml_key(key),
682                yaml_scalar(value, original)
683            ));
684        }
685    }
686}
687
688fn render_yaml_array_raw(
689    arr: &[Value],
690    original: Option<&DocumentValue>,
691    indent: usize,
692    lines: &mut Vec<String>,
693) {
694    let prefix = "  ".repeat(indent);
695    for (index, item) in arr.iter().enumerate() {
696        let original = original
697            .and_then(DocumentValue::as_array)
698            .and_then(|array| array.get(index));
699        match item {
700            Value::Object(inner) if !inner.is_empty() => {
701                lines.push(format!("{prefix}-"));
702                render_yaml_raw(item, original, indent + 1, lines);
703            }
704            Value::Array(nested) if !nested.is_empty() => {
705                lines.push(format!("{prefix}-"));
706                render_yaml_array_raw(nested, original, indent + 1, lines);
707            }
708            Value::Object(_) => {
709                lines.push(format!("{prefix}- {{}}"));
710            }
711            Value::Array(_) => {
712                lines.push(format!("{prefix}- []"));
713            }
714            _ => {
715                lines.push(format!("{}- {}", prefix, yaml_scalar(item, original)));
716            }
717        }
718    }
719}
720
721pub(crate) fn escape_yaml_str(s: &str) -> String {
722    let mut escaped = String::with_capacity(s.len());
723    for character in s.chars() {
724        match character {
725            '\\' => escaped.push_str("\\\\"),
726            '"' => escaped.push_str("\\\""),
727            '\n' => escaped.push_str("\\n"),
728            '\r' => escaped.push_str("\\r"),
729            '\t' => escaped.push_str("\\t"),
730            '\x08' => escaped.push_str("\\b"),
731            '\x0c' => escaped.push_str("\\f"),
732            '\x0b' => escaped.push_str("\\v"),
733            '\0' => escaped.push_str("\\0"),
734            control
735                if control.is_control()
736                    || matches!(control, '\u{2028}' | '\u{2029}' | '\u{fffe}' | '\u{ffff}') =>
737            {
738                use std::fmt::Write as _;
739                let _ = write!(escaped, "\\u{:04x}", control as u32);
740            }
741            other => escaped.push(other),
742        }
743    }
744    escaped
745}
746
747fn yaml_key(key: &str) -> String {
748    if is_safe_key(key) && !is_ambiguous_yaml_key(key) {
749        key.to_string()
750    } else {
751        format!("\"{}\"", escape_yaml_str(key))
752    }
753}
754
755fn is_ambiguous_yaml_key(key: &str) -> bool {
756    let lower = key.to_ascii_lowercase();
757    matches!(
758        lower.as_str(),
759        "true" | "false" | "null" | "~" | ".nan" | ".inf" | "+.inf" | "-.inf"
760    ) || matches!(lower.trim_prefix(['+', '-']), "inf" | "infinity" | "nan")
761        || is_decimal_yaml_key(key)
762}
763
764fn is_decimal_yaml_key(key: &str) -> bool {
765    let mut bytes = key.bytes().peekable();
766    if matches!(bytes.peek(), Some(b'+' | b'-')) {
767        bytes.next();
768    }
769    let mut digits = 0;
770    while bytes.next_if(u8::is_ascii_digit).is_some() {
771        digits += 1;
772    }
773    if bytes.next_if_eq(&b'.').is_some() {
774        while bytes.next_if(u8::is_ascii_digit).is_some() {
775            digits += 1;
776        }
777    }
778    if digits == 0 {
779        return false;
780    }
781    if matches!(bytes.peek(), Some(b'e' | b'E')) {
782        bytes.next();
783        if matches!(bytes.peek(), Some(b'+' | b'-')) {
784            bytes.next();
785        }
786        let mut exponent_digits = 0;
787        while bytes.next_if(u8::is_ascii_digit).is_some() {
788            exponent_digits += 1;
789        }
790        if exponent_digits == 0 {
791            return false;
792        }
793    }
794    bytes.next().is_none()
795}
796
797fn quote_logfmt_key(key: &str) -> String {
798    if is_safe_key(key) {
799        key.to_string()
800    } else {
801        quote_logfmt_value(key)
802    }
803}
804
805fn is_safe_key(key: &str) -> bool {
806    !key.is_empty()
807        && key
808            .bytes()
809            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-' | b'.'))
810}
811
812fn yaml_scalar(value: &Value, original: Option<&DocumentValue>) -> String {
813    if let (Value::String(text), Some(DocumentValue::Float(number))) = (value, original)
814        && !number.is_finite()
815        && text == non_finite_spelling(*number)
816    {
817        return text.clone();
818    }
819    match value {
820        Value::String(s) => format!("\"{}\"", escape_yaml_str(s)),
821        Value::Null => "null".to_string(),
822        Value::Bool(b) => b.to_string(),
823        Value::Number(n) => format_number(n),
824        Value::Object(_) | Value::Array(_) => {
825            format!("\"{}\"", escape_yaml_str(&embedded_json(value)))
826        }
827    }
828}
829
830// ═══════════════════════════════════════════
831// Plain Rendering (logfmt)
832// ═══════════════════════════════════════════
833
834fn collect_plain_pairs(value: &Value, prefix: &str, pairs: &mut Vec<(String, String)>) {
835    if let Value::Object(map) = value {
836        let processed = process_object_fields(map);
837        for (display_key, v, formatted) in processed {
838            let full_key = if prefix.is_empty() {
839                display_key
840            } else {
841                format!("{prefix}.{display_key}")
842            };
843            if let Some(fv) = formatted {
844                pairs.push((full_key, fv));
845            } else {
846                match v {
847                    Value::Object(map) if map.is_empty() => {
848                        pairs.push((full_key, "{}".to_string()));
849                    }
850                    Value::Object(_) => collect_plain_pairs(v, &full_key, pairs),
851                    Value::Array(arr) if arr.is_empty() => {
852                        pairs.push((full_key, "[]".to_string()));
853                    }
854                    Value::Array(arr) => {
855                        let joined = arr.iter().map(plain_scalar).collect::<Vec<_>>().join(",");
856                        pairs.push((full_key, joined));
857                    }
858                    Value::Null => pairs.push((full_key, String::new())),
859                    _ => pairs.push((full_key, plain_scalar(v))),
860                }
861            }
862        }
863    }
864}
865
866fn collect_plain_pairs_raw(value: &Value, prefix: &str, pairs: &mut Vec<(String, String)>) {
867    if let Value::Object(map) = value {
868        for key in sorted_value_keys(map) {
869            let v = &map[&key];
870            let full_key = if prefix.is_empty() {
871                key.clone()
872            } else {
873                format!("{prefix}.{key}")
874            };
875            match v {
876                Value::Object(map) if map.is_empty() => {
877                    pairs.push((full_key, "{}".to_string()));
878                }
879                Value::Object(_) => collect_plain_pairs_raw(v, &full_key, pairs),
880                Value::Array(arr) if arr.is_empty() => {
881                    pairs.push((full_key, "[]".to_string()));
882                }
883                Value::Array(arr) => {
884                    let joined = arr.iter().map(plain_scalar).collect::<Vec<_>>().join(",");
885                    pairs.push((full_key, joined));
886                }
887                Value::Null => pairs.push((full_key, String::new())),
888                _ => pairs.push((full_key, plain_scalar(v))),
889            }
890        }
891    }
892}
893
894fn plain_scalar(value: &Value) -> String {
895    match value {
896        Value::String(s) => s.clone(),
897        Value::Null => "null".to_string(),
898        Value::Bool(b) => b.to_string(),
899        Value::Number(n) => format_number(n),
900        Value::Object(_) | Value::Array(_) => embedded_json(value),
901    }
902}
903
904fn quote_logfmt_value(value: &str) -> String {
905    if !value
906        .chars()
907        .any(|c| is_plain_control(c) || matches!(c, ' ' | '\u{a0}' | '=' | '"' | '\\'))
908    {
909        return value.to_string();
910    }
911    format!("\"{}\"", escape_plain_text(value, true))
912}
913
914fn is_plain_control(c: char) -> bool {
915    c.is_control() || matches!(c, '\u{2028}' | '\u{2029}')
916}
917
918fn escape_plain_text(value: &str, escape_quotes: bool) -> String {
919    use std::fmt::Write as _;
920
921    let mut escaped = String::with_capacity(value.len());
922    for c in value.chars() {
923        match c {
924            '\\' | '"' if escape_quotes => {
925                escaped.push('\\');
926                escaped.push(c);
927            }
928            c if is_plain_control(c) => {
929                let _ = write!(escaped, "\\u{{{:04x}}}", u32::from(c));
930            }
931            c => escaped.push(c),
932        }
933    }
934    escaped
935}
936
937/// A container inside a Plain array (or a YAML scalar position) is written as
938/// compact JSON with sorted keys. Its number leaves take the canonical number
939/// form, the same text the value prints as a scalar, so a nested `1.0` reads
940/// `1` and a decoded `1e5` reads `100000` in every SDK rather than in each
941/// runtime's own JSON spelling.
942fn embedded_json(value: &Value) -> String {
943    let mut out = String::new();
944    write_embedded_json(value, &mut out);
945    out
946}
947
948fn write_embedded_json(value: &Value, out: &mut String) {
949    match value {
950        Value::Object(map) => {
951            out.push('{');
952            for (index, key) in sorted_value_keys(map).iter().enumerate() {
953                if index > 0 {
954                    out.push(',');
955                }
956                write_json_string(key, out);
957                out.push(':');
958                write_embedded_json(&map[key], out);
959            }
960            out.push('}');
961        }
962        Value::Array(items) => {
963            out.push('[');
964            for (index, item) in items.iter().enumerate() {
965                if index > 0 {
966                    out.push(',');
967                }
968                write_embedded_json(item, out);
969            }
970            out.push(']');
971        }
972        Value::String(text) => write_json_string(text, out),
973        Value::Number(number) => out.push_str(&format_number(number)),
974        Value::Bool(flag) => out.push_str(if *flag { "true" } else { "false" }),
975        Value::Null => out.push_str("null"),
976    }
977}
978
979fn write_json_string(text: &str, out: &mut String) {
980    // Serializing a `str` cannot fail; the fallback keeps this infallible.
981    out.push_str(&serde_json::to_string(text).unwrap_or_else(|_| "\"\"".to_string()));
982}
983
984fn sorted_value_keys(map: &serde_json::Map<String, Value>) -> Vec<String> {
985    let mut keys: Vec<String> = map.keys().cloned().collect();
986    keys.sort_by(|a, b| a.encode_utf16().cmp(b.encode_utf16()));
987    keys
988}
989
990#[cfg(test)]
991mod tests {
992    use super::*;
993    use crate::redaction::{RedactionPolicy, Redactor};
994    use serde_json::json;
995
996    fn plain(value: &Value, policy: RedactionPolicy) -> String {
997        render(
998            value,
999            OutputFormat::Plain,
1000            &OutputOptions {
1001                redaction: Redactor::new().policy(policy),
1002                style: PlainStyle::Readable,
1003            },
1004        )
1005    }
1006
1007    // ── `_secret` stripping follows redaction ──────────
1008
1009    #[test]
1010    fn plain_strips_secret_suffix_once_the_value_is_redacted() {
1011        assert_eq!(
1012            plain(
1013                &json!({"api_key_secret": "sk-live-xxx"}),
1014                RedactionPolicy::All
1015            ),
1016            "api_key=***"
1017        );
1018    }
1019
1020    #[test]
1021    fn plain_keeps_secret_suffix_when_redaction_is_off() {
1022        // Stripping here would hand a live credential to a reader under a name
1023        // that no longer says it is one.
1024        assert_eq!(
1025            plain(
1026                &json!({"api_key_secret": "sk-live-xxx"}),
1027                RedactionPolicy::Off
1028            ),
1029            "api_key_secret=sk-live-xxx"
1030        );
1031        assert_eq!(
1032            plain(
1033                &json!({"API_KEY_SECRET": "sk-live-xxx"}),
1034                RedactionPolicy::Off
1035            ),
1036            "API_KEY_SECRET=sk-live-xxx"
1037        );
1038    }
1039
1040    #[test]
1041    fn plain_keeps_secret_suffix_outside_trace_under_trace_only() {
1042        assert_eq!(
1043            plain(
1044                &json!({
1045                    "api_key_secret": "sk-live-xxx",
1046                    "trace": {"request_secret": "top-secret"}
1047                }),
1048                RedactionPolicy::TraceOnly
1049            ),
1050            "api_key_secret=sk-live-xxx trace.request=***"
1051        );
1052    }
1053
1054    #[test]
1055    fn plain_keeps_secret_suffix_on_an_unredacted_subtree() {
1056        assert_eq!(
1057            plain(
1058                &json!({"db_secret": {"password": "hunter2"}}),
1059                RedactionPolicy::Off
1060            ),
1061            "db_secret.password=hunter2"
1062        );
1063        assert_eq!(
1064            plain(
1065                &json!({"db_secret": {"password": "hunter2"}}),
1066                RedactionPolicy::All
1067            ),
1068            "db=***"
1069        );
1070    }
1071
1072    #[test]
1073    fn plain_unstripped_secret_key_does_not_collide_with_its_stem() {
1074        // Keeping the suffix also means no collision to fall back from: both
1075        // fields keep their own name and value.
1076        assert_eq!(
1077            plain(
1078                &json!({"api_key": "public", "api_key_secret": "sk-live-xxx"}),
1079                RedactionPolicy::Off
1080            ),
1081            "api_key=public api_key_secret=sk-live-xxx"
1082        );
1083    }
1084}