//! Character-level hygiene for WhatsApp's text export — the port of //! `packages/import-core/src/text.ts`. //! //! WhatsApp writes its `_chat.txt` for a bidirectional world: lines are //! wrapped in Unicode direction controls so an Arabic name inside an English //! timestamp renders correctly. Those controls are INVISIBLE, so a parser that //! forgets them fails in a way nobody can see in a diff — the line regex //! simply does not match, the line becomes a continuation of the previous //! message, and the whole file silently collapses into one giant message. //! //! Newer iOS/Android builds also write U+202F (NARROW NO-BREAK SPACE) before //! AM/PM instead of a normal space, which breaks any `\s`-naive matcher for //! the same invisible reason. //! //! The character classes are BUILT FROM CODE POINTS rather than written as //! literals, exactly as the TypeScript does and for the same reason: an //! invisible character in source is unreviewable, it does not survive a //! careless copy-paste, and a reader cannot tell U+200E from U+200F by //! looking. Here the source is pure ASCII and says which code points it //! removes. use crate::js; /// LRM, RLM, ALM and the isolate family (LRI / RLI / FSI / PDI). const BIDI_CODE_POINTS: [char; 7] = [ '\u{200e}', '\u{200f}', '\u{061c}', '\u{2066}', '\u{2067}', '\u{2068}', '\u{2069}', ]; /// Spaces WhatsApp emits that are not U+0020: NBSP, figure, thin, hair, NNBSP. const EXOTIC_SPACE_CODE_POINTS: [char; 5] = ['\u{00a0}', '\u{2007}', '\u{2009}', '\u{200a}', '\u{202f}']; const BOM: char = '\u{feff}'; pub fn strip_bidi(input: &str) -> String { input .chars() .filter(|ch| !BIDI_CODE_POINTS.contains(ch)) .collect() } pub fn normalize_spaces(input: &str) -> String { input .chars() .map(|ch| { if EXOTIC_SPACE_CODE_POINTS.contains(&ch) { ' ' } else { ch } }) .collect() } /// A BOM only where a BOM means something — at the very front. A U+FEFF in the /// middle of a body is a zero-width no-break space somebody typed, and it is /// left alone (the TypeScript's `startsWith` + `slice(1)`). pub fn strip_bom(input: &str) -> String { input.strip_prefix(BOM).unwrap_or(input).to_string() } /// The full pre-parse pass: strip the BOM, drop direction controls, fold /// exotic spaces, and normalize CRLF/CR to LF so line splitting is one rule. /// /// It runs on the WHOLE file before splitting, and its output is also what /// message bodies are built from — so an emoji-heavy body survives untouched /// while its invisible scaffolding does not. pub fn normalize_export_text(input: &str) -> String { let folded = normalize_spaces(&strip_bidi(&strip_bom(input))); // JS `replace(/\r\n?/g, "\n")`: a CR swallows a following LF, and a lone // CR becomes an LF on its own. let mut out = String::with_capacity(folded.len()); let mut chars = folded.chars().peekable(); while let Some(ch) = chars.next() { if ch == '\r' { if chars.peek() == Some(&'\n') { chars.next(); } out.push('\n'); } else { out.push(ch); } } out } /// Collapse runs of whitespace and trim — the shape hashed into a fallback id. /// /// Delegated to the store's `collapse_whitespace_and_trim` rather than /// re-implemented, because it is the SAME operation the content fingerprint /// performs on a body (`normalize_body_for_id`) and the two must never drift: /// the whitespace class is ECMAScript's (U+FEFF in, U+0085 out), not Rust's /// `char::is_whitespace`, which has it the other way round in both /// directions. `collapseWhitespace("a\u{feff}b")` is `"a b"`, and /// `collapseWhitespace("a\u{85}b")` is `"a\u{85}b"`; both are pinned by Node /// vector in `text_tests.rs`. pub fn collapse_whitespace(input: &str) -> String { js::collapse_whitespace_and_trim(input) } /// JS `String.prototype.trim()` — the ECMAScript whitespace class, not Rust's. /// /// Used wherever the TypeScript trims a field whose emptiness decides /// something (a poll's question, an owner name, a group title). `str::trim` /// would disagree on a BOM-only string, which is exactly the shape that /// decides whether a body counts as blank. pub fn js_trim(input: &str) -> &str { input.trim_matches(js::is_js_whitespace) } /// JS `String.prototype.trimStart()`. pub fn js_trim_start(input: &str) -> &str { input.trim_start_matches(js::is_js_whitespace) } /// The ECMAScript `\s` class, spelled as a regex character class so a ported /// pattern means the same thing on both sides. Rust's own `\s` is the Unicode /// `White_Space` property: it EXCLUDES U+FEFF and INCLUDES U+0085, and either /// difference changes where a poll keyword or an option's text ends. pub const JS_WHITESPACE_CLASS: &str = r"\t\n\x0B\f\r \u{a0}\u{1680}\u{2000}-\u{200a}\u{2028}\u{2029}\u{202f}\u{205f}\u{3000}\u{feff}"; /// The ECMAScript `.` class (any code point except a LineTerminator). Rust's /// `.` excludes only `\n`, so a body carrying U+2028 would match differently. pub const JS_DOT_CLASS: &str = r"[^\n\r\u{2028}\u{2029}]"; /// UTF-16 code units, because `String.prototype.length` counts those and every /// length test ported out of this package is a JavaScript `.length`. pub fn utf16_len(input: &str) -> usize { input.encode_utf16().count() } #[cfg(test)] #[path = "text_tests.rs"] mod tests;