//! Deterministic, zero-dependency JSON serializer for `ForensicReport`. //! //! Escapes all control characters, quotes, backslashes, and `<` (`\u003c`) so emitted JSON //! is safe across DOM, SSR, and WebAssembly memory bridges without pulling in external crates. use std::fmt::Write as _; use crate::model::{ForensicReport, SentenceForensic}; /// Appends a JSON-escaped string literal (including surrounding `"`) to `out`. pub fn push_json_str(out: &mut String, value: &str) { out.push('"'); for ch in value.chars() { match ch { '"' => out.push_str("\\\""), '\\' => out.push_str("\\\\"), '\n' => out.push_str("\\n"), '\r' => out.push_str("\\r"), '\t' => out.push_str("\\t"), '<' => out.push_str("\\u003c"), c if (c as u32) < 0x20 => { let _ = write!(out, "\\u{:04x}", c as u32); } c => out.push(c), } } out.push('"'); } fn round3(v: f64) -> f64 { if v.is_finite() { ((v * 1000.0).round()) / 1000.0 } else { 0.0 } } fn push_sentence_json(out: &mut String, s: &SentenceForensic) { let _ = write!( out, "{{\"index\":{},\"unitLen\":{},\"aiPct\":{:.1},\"gltrBand\":\"{}\",\"reason\":", s.index, s.unit_len, s.ai_score.as_percent(), s.gltr_band.slug() ); push_json_str(out, s.reason_code); let _ = write!(out, ",\"phraseHits\":{},\"text\":", s.phrase_hits); push_json_str(out, &s.text); out.push('}'); } /// Serializes a `ForensicReport` into a compact UTF-8 JSON document. #[must_use] pub fn serialize_report_json(report: &ForensicReport) -> String { let mut out = String::with_capacity(2048 + report.byte_len); let g0 = report.gltr_counts.first().copied().unwrap_or(0); let g1 = report.gltr_counts.get(1).copied().unwrap_or(0); let g2 = report.gltr_counts.get(2).copied().unwrap_or(0); let g3 = report.gltr_counts.get(3).copied().unwrap_or(0); let _ = write!( out, "{{\"modelEngine\":\"gbdt_treeshap_v2\",\"aiPct\":{:.1},\"humanPct\":{:.1},\"confidencePct\":{:.1},\"mleAlphaPct\":{:.1},\"hurstExponent\":{:.3},\"graphClustering\":{:.3},\"ppmLlrBits\":{:.3},\"nbsvmMargin\":{:.3},\"verdict\":\"{}\",\"scriptFamily\":\"{}\",\"genre\":\"{}\",\"byteLen\":{},\"charCount\":{},\"tokenCount\":{},\"sentenceCount\":{},\"meanSentenceLen\":{:.2},\"stdSentenceLen\":{:.2},\"burstinessCv\":{:.3},\"mattr50\":{:.3},\"hapaxRatio\":{:.3},\"lz77Ratio\":{:.3},\"conditionalEntropyBits\":{:.3},\"crossEntropyRatio\":{:.3},\"removableWatermarkChars\":{},", report.overall_ai_score.as_percent(), report.overall_human_score.as_percent(), report.confidence.as_percent(), report.mle_alpha_fraction.as_percent(), round3(report.hurst_exponent), round3(report.graph_clustering), round3(report.ppm_llr_bits), round3(report.nbsvm_margin), report.verdict.slug(), report.script_family.slug(), report.genre.slug(), report.byte_len, report.char_count, report.token_count, report.sentence_count, round3(report.mean_sentence_len), round3(report.std_sentence_len), round3(report.burstiness_cv), round3(report.mattr_50), round3(report.hapax_ratio), round3(report.lz77_ratio), round3(report.conditional_entropy_bits), round3(report.cross_entropy_ratio), report.removable_watermark_chars, ); let sf = &report.shap_families; let _ = write!( out, "\"shapLogOdds\":{{\"ppm\":{:.3},\"diveye\":{:.3},\"cadence\":{:.3},\"mleGraph\":{:.3},\"nbsvm\":{:.3}}},", round3(sf.first().copied().unwrap_or(0.0)), round3(sf.get(1).copied().unwrap_or(0.0)), round3(sf.get(2).copied().unwrap_or(0.0)), round3(sf.get(3).copied().unwrap_or(0.0)), round3(sf.get(4).copied().unwrap_or(0.0)), ); let d = &report.dimensions; let _ = write!( out, "\"dimensions\":{{\"compression\":{:.1},\"crossEntropy\":{:.1},\"cadence\":{:.1},\"lexical\":{:.1},\"discourse\":{:.1},\"watermarks\":{:.1}}},", d.compression_predictability.as_percent(), d.cross_entropy_curvature.as_percent(), d.cadence_uniformity.as_percent(), d.lexical_concentration.as_percent(), d.discourse_template_signal.as_percent(), d.watermark_artifact_signal.as_percent(), ); let _ = write!( out, "\"gltrCounts\":{{\"green\":{g0},\"yellow\":{g1},\"red\":{g2},\"violet\":{g3}}},\"matchedPhrases\":[" ); for (i, phrase) in report.matched_phrases.iter().enumerate() { if i > 0 { out.push(','); } push_json_str(&mut out, phrase); } out.push_str("],\"watermarkFindings\":["); for (i, wf) in report.watermark_findings.iter().enumerate() { if i > 0 { out.push(','); } out.push_str("{\"code\":"); push_json_str(&mut out, wf.code); out.push_str(",\"label\":"); push_json_str(&mut out, wf.label); let _ = write!(out, ",\"count\":{}}}", wf.count); } out.push_str("],\"sentences\":["); for (i, sent) in report.sentences.iter().enumerate() { if i > 0 { out.push(','); } push_sentence_json(&mut out, sent); } out.push_str("]}"); out }