laratext 0.1.0

Laratext for Laravel Rust: translation keys with their source text, and auto-translation with OpenAI, Claude, Google Translate or Translatorio.
Documentation
use serde::Serialize;
use serde_json::Serializer;
use serde_json::ser::PrettyFormatter;

/// `json_encode($value, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)`, with or without
/// `JSON_UNESCAPED_SLASHES`: four spaces of indentation, and `/` written as `\/` unless
/// `unescaped_slashes` is set.
pub fn pretty(value: &impl Serialize, unescaped_slashes: bool) -> String {
    let mut buffer = Vec::new();
    let mut serializer = Serializer::with_formatter(&mut buffer, PrettyFormatter::with_indent(b"    "));

    value
        .serialize(&mut serializer)
        .expect("a value of this crate serialises");

    // Neither character can appear outside a string, so replacing them everywhere is safe.
    let json = String::from_utf8(buffer).expect("JSON is UTF-8");
    let json = escape_line_terminators(&json);

    if unescaped_slashes {
        json
    } else {
        json.replace('/', "\\/")
    }
}

/// The compact `json_encode` of a payload printed in a script tag: `<` and `>` become `\u003C` and
/// `\u003E` (`JSON_HEX_TAG`), so a translation can never close the tag.
pub fn for_script(value: &impl Serialize) -> String {
    let json = serde_json::to_string(value).expect("a value of this crate serialises");

    escape_line_terminators(&json)
        .replace('<', "\\u003C")
        .replace('>', "\\u003E")
}

fn escape_line_terminators(json: &str) -> String {
    json.replace('\u{2028}', "\\u2028").replace('\u{2029}', "\\u2029")
}