//! The word-level and field-level diff behind record history. //! //! Both halves are pure and library-free on purpose: history is drawn on a //! phone from rows the database wrote, and a diff that needs a dependency is a //! diff that can disagree with itself between the app and anything else that //! later reads the same trail. use serde_json::json; use super::*; /// `same/added/removed` runs as a compact string, for readable assertions — /// the TypeScript test's own `shape` helper. fn shape(spans: &[WordSpan]) -> String { spans .iter() .map(|s| format!("{}:{}", &s.kind.as_str()[..1], s.text)) .collect::>() .join("|") } fn row(value: serde_json::Value) -> RecordRow { match value { serde_json::Value::Object(map) => map, other => panic!("a row fixture must be an object, got {other}"), } } /// `Array.from({ length: n }, (_, i) => `${prefix}${i}`).join(" ")`. fn words(prefix: &str, n: usize) -> String { (0..n) .map(|i| format!("{prefix}{i}")) .collect::>() .join(" ") } // ── diffWords ──────────────────────────────────────────────────────────────── #[test] fn returns_one_unchanged_span_when_the_text_did_not_change() { assert_eq!( diff_words("hello there", "hello there"), vec![WordSpan { kind: WordSpanKind::Same, text: "hello there".to_string() }] ); } #[test] fn returns_nothing_for_two_empty_strings() { assert_eq!(diff_words("", ""), Vec::::new()); } #[test] fn marks_the_whole_of_a_first_draft_as_added() { assert_eq!( diff_words("", "a start"), vec![WordSpan { kind: WordSpanKind::Added, text: "a start".to_string() }] ); } #[test] fn marks_emptied_text_as_removed() { assert_eq!( diff_words("gone now", ""), vec![WordSpan { kind: WordSpanKind::Removed, text: "gone now".to_string() }] ); } #[test] fn tints_only_the_word_that_changed() { assert_eq!( shape(&diff_words("call the plumber", "call the electrician")), "s:call the |r:plumber|a:electrician" ); } #[test] fn marks_an_inserted_word_without_touching_its_neighbours() { assert_eq!( shape(&diff_words("call plumber", "call the plumber")), "s:call |a:the |s:plumber" ); } #[test] fn marks_a_deleted_word_without_touching_its_neighbours() { assert_eq!( shape(&diff_words("call the plumber", "call plumber")), "s:call |r:the |s:plumber" ); } #[test] fn keeps_line_breaks_so_a_paragraph_split_reads_as_one_insertion() { assert_eq!( shape(&diff_words("one two", "one\ntwo")), "s:one|r: |a:\n|s:two" ); } #[test] fn merges_neighbouring_runs_of_the_same_kind_into_one_span() { assert_eq!(shape(&diff_words("a b c", "c")), "r:a b |s:c"); } #[test] fn keeps_the_shared_words_either_side_of_a_rewritten_middle() { assert_eq!( shape(&diff_words("a b c", "x y c")), "r:a|a:x|s: |r:b|a:y|s: c" ); } #[test] fn is_case_sensitive_a_capital_is_an_edit() { assert_eq!( shape(&diff_words("plumber", "Plumber")), "r:plumber|a:Plumber" ); } #[test] fn handles_a_word_repeated_on_both_sides_without_crossing_the_pairs() { assert_eq!( shape(&diff_words("the the end", "the end")), "s:the |r:the |s:end" ); } /// Nothing shared at either end, so the trim cannot shrink the middle. #[test] fn falls_back_to_a_whole_block_replacement_past_the_token_ceiling() { let before = words("a", 800); let after = words("b", 800); assert_eq!( diff_words(&before, &after), vec![ WordSpan { kind: WordSpanKind::Removed, text: before.clone() }, WordSpan { kind: WordSpanKind::Added, text: after.clone() }, ] ); } #[test] fn still_diffs_a_long_text_whose_edit_is_a_small_middle() { let head = words("a", 800); let tail = words("z", 800); assert_eq!( shape(&diff_words( &format!("{head} one {tail}"), &format!("{head} two {tail}") )), format!("s:{head} |r:one|a:two|s: {tail}") ); } #[test] fn still_diffs_word_by_word_just_under_the_ceiling() { let text = words("w", 100); assert_eq!( diff_words(&text, &format!("{text} tail")), vec![ WordSpan { kind: WordSpanKind::Same, text: text.clone() }, WordSpan { kind: WordSpanKind::Added, text: " tail".to_string() }, ] ); } // ── diffWords: Node vectors ────────────────────────────────────────────────── // // Forty-one pairs were run through the TypeScript; the twelve above are its own // test file's, and these are the rest. Every expected string below was printed // by Node, never reasoned out. #[test] fn word_vectors_match_the_typescript_shape_for_shape() { let vectors: &[(&str, &str, &str)] = &[ (" ", " ", "r: |a: "), (" ", "", "r: "), ("a", "a ", "s:a|a: "), ("a b", "a b", "s:a|r: |a: |s:b"), ( "one two three", "one three two", "s:one |r:two |s:three|a: two", ), ( "Roof tiles leak", "Roof tiles leak badly", "s:Roof tiles leak|a: badly", ), // No normalisation: a combining acute and a precomposed é are two // different words, so the whole token is replaced. ("cafe\u{301}", "caf\u{e9}", "r:cafe\u{301}|a:caf\u{e9}"), // NBSP is `\s`, so it is a token of its own and the words either side // stay untinted. ("a\u{a0}b", "a b", "s:a|r:\u{a0}|a: |s:b"), ("a\u{feff}b", "a b", "s:a|r:\u{feff}|a: |s:b"), // U+0085 is NOT `\s` in JavaScript, so `a\u{85}b` is ONE token and the // whole thing is replaced. ("a\u{85}b", "a b", "r:a\u{85}b|a:a b"), ("a\u{3000}b", "a b", "s:a|r:\u{3000}|a: |s:b"), ( "fix the roof", "fix the roof\n\nand the gutter", "s:fix the roof|a:\n\nand the gutter", ), ("x", "y", "r:x|a:y"), ( "the cat sat on the mat", "the dog sat on the mat", "s:the |r:cat|a:dog|s: sat on the mat", ), ( "the cat sat on the mat", "the mat sat on the cat", "s:the |r:cat|a:mat|s: sat on the |r:mat|a:cat", ), ("abc def", "abc def ghi jkl", "s:abc def|a: ghi jkl"), ( "1 2 3 4 5", "5 4 3 2 1", "r:1|a:5|s: |r:2|a:4|s: 3 |r:4|a:2|s: |r:5|a:1", ), ("hello", "hello world hello", "s:hello|a: world hello"), ("a\tb", "a\nb", "s:a|r:\t|a:\n|s:b"), ("\n\n", "\n", "r:\n\n|a:\n"), ("one", "one one", "s:one|a: one"), ("one one", "one", "s:one|r: one"), ( "emoji \u{1f600} ok", "emoji \u{1f600} ok", "s:emoji \u{1f600} ok", ), ("na\u{ef}ve", "na\u{ef}ve", "s:na\u{ef}ve"), ]; for (before, after, expected) in vectors { assert_eq!(shape(&diff_words(before, after)), *expected, "{before:?}"); } } /// The ceiling is counted in TOKENS, not words, and the whitespace between two /// words is a token — so 300 words (599 tokens) still align and 301 (601) do /// not. Both counts were read out of Node. #[test] fn the_token_ceiling_falls_between_five_hundred_and_ninety_nine_and_six_hundred_and_one() { let under = diff_words(&words("a", 300), &words("b", 300)); assert_eq!(under.len(), 899); assert_eq!(under[0].text, "a0"); assert_eq!(under[1].text, "b0"); assert_eq!(under[2].text, " "); assert_eq!(under[2].kind, WordSpanKind::Same); assert_eq!(under[under.len() - 2].text, "a299"); assert_eq!(under[under.len() - 1].text, "b299"); let over = diff_words(&words("a", 301), &words("b", 301)); assert_eq!(over.len(), 2); assert_eq!(over[0].kind, WordSpanKind::Removed); assert_eq!(over[1].kind, WordSpanKind::Added); assert_eq!(over[0].text, words("a", 301)); } // ── diffFields ─────────────────────────────────────────────────────────────── const COLUMNS: [&str; 3] = ["title", "body", "due_at"]; #[test] fn reports_nothing_when_every_column_matches() { let before = row(json!({ "title": "Roof", "body": "leak", "due_at": null })); let after = before.clone(); assert_eq!(diff_fields(&before, Some(&after), &COLUMNS), vec![]); } #[test] fn reports_a_changed_column_with_both_values() { assert_eq!( diff_fields( &row(json!({ "title": "Roof", "body": "leak", "due_at": null })), Some(&row( json!({ "title": "Roof tiles", "body": "leak", "due_at": null }) )), &COLUMNS, ), vec![FieldChange { column: "title".to_string(), change: FieldChangeKind::Changed, before: json!("Roof"), after: json!("Roof tiles"), }] ); } #[test] fn calls_a_column_filled_from_empty_an_addition() { assert_eq!( diff_fields( &row(json!({ "due_at": null })), Some(&row(json!({ "due_at": "2026-09-04" }))), &["due_at"], ), vec![FieldChange { column: "due_at".to_string(), change: FieldChangeKind::Added, before: json!(null), after: json!("2026-09-04"), }] ); } #[test] fn treats_an_absent_key_and_a_null_as_the_same_emptiness() { assert_eq!( diff_fields( &row(json!({})), Some(&row(json!({ "due_at": null }))), &["due_at"] ), vec![] ); } #[test] fn treats_a_whitespace_only_string_as_empty() { assert_eq!( diff_fields( &row(json!({ "body": " " })), Some(&row(json!({ "body": "" }))), &["body"], ), vec![] ); assert_eq!( diff_fields( &row(json!({ "body": " " })), Some(&row(json!({ "body": "words" }))), &["body"], ), vec![FieldChange { column: "body".to_string(), change: FieldChangeKind::Added, before: json!(" "), after: json!("words"), }] ); } #[test] fn calls_a_column_emptied_a_removal() { assert_eq!( diff_fields( &row(json!({ "body": "leak" })), Some(&row(json!({ "body": null }))), &["body"], ), vec![FieldChange { column: "body".to_string(), change: FieldChangeKind::Removed, before: json!("leak"), after: json!(null), }] ); } #[test] fn does_not_call_zero_or_false_empty() { assert_eq!( diff_fields( &row(json!({ "n": 0 })), Some(&row(json!({ "n": 1 }))), &["n"] ), vec![FieldChange { column: "n".to_string(), change: FieldChangeKind::Changed, before: json!(0), after: json!(1), }] ); assert_eq!( diff_fields( &row(json!({ "f": false })), Some(&row(json!({ "f": null }))), &["f"], ), vec![FieldChange { column: "f".to_string(), change: FieldChangeKind::Removed, before: json!(false), after: json!(null), }] ); } #[test] fn compares_numbers_and_their_string_spellings_as_equal() { assert_eq!( diff_fields( &row(json!({ "n": 1 })), Some(&row(json!({ "n": "1" }))), &["n"] ), vec![] ); } #[test] fn compares_json_values_by_content_not_by_key_order() { assert_eq!( diff_fields( &row(json!({ "meta": { "a": 1, "b": 2 } })), Some(&row(json!({ "meta": { "b": 2, "a": 1 } }))), &["meta"], ), vec![] ); assert_eq!( diff_fields( &row(json!({ "meta": { "a": 1 } })), Some(&row(json!({ "meta": { "a": 2 } }))), &["meta"], ), vec![FieldChange { column: "meta".to_string(), change: FieldChangeKind::Changed, before: json!({ "a": 1 }), after: json!({ "a": 2 }), }] ); } #[test] fn reads_only_the_columns_it_is_given_in_that_order() { let changes = diff_fields( &row(json!({ "body": "old", "title": "old", "ignored": "old" })), Some(&row( json!({ "body": "new", "title": "new", "ignored": "new" }), )), &["title", "body"], ); assert_eq!( changes .iter() .map(|c| c.column.as_str()) .collect::>(), ["title", "body"] ); } #[test] fn reports_every_column_as_removed_when_the_record_was_deleted() { assert_eq!( diff_fields( &row(json!({ "title": "Roof", "body": "leak" })), None, &COLUMNS ), vec![ FieldChange { column: "title".to_string(), change: FieldChangeKind::Removed, before: json!("Roof"), after: json!(null), }, FieldChange { column: "body".to_string(), change: FieldChangeKind::Removed, before: json!("leak"), after: json!(null), }, ] ); } // ── diffFields: Node vectors ───────────────────────────────────────────────── // // Thirty-four field cases were run through the TypeScript; the thirteen above // are its own test file's, and the twenty-one below are the rest. Several // corrected a guess. /// A compact rendering of one change, so a whole vector table reads at a /// glance: `column/kind/before/after` with both values as JSON. fn changes_shape(changes: &[FieldChange]) -> String { changes .iter() .map(|c| { format!( "{}/{}/{}/{}", c.column, c.change.as_str(), serde_json::to_string(&c.before).expect("a Value serialises"), serde_json::to_string(&c.after).expect("a Value serialises"), ) }) .collect::>() .join(" ") } #[test] fn field_vectors_match_the_typescript() { let vectors: &[(&str, serde_json::Value, serde_json::Value, &[&str], &str)] = &[ ( "float vs spelling", json!({ "n": 1.5 }), json!({ "n": "1.5" }), &["n"], "", ), ( "float vs trailing zero", json!({ "n": 1.5 }), json!({ "n": "1.50" }), &["n"], "n/changed/1.5/\"1.50\"", ), // `String(1e21)` is "1e+21", so the number and that spelling agree. ( "big int spelling", json!({ "n": 1e21 }), json!({ "n": "1e+21" }), &["n"], "", ), // The surprise: `String(true)` IS "true", so a boolean and its spelling // compare EQUAL. ( "true vs string", json!({ "f": true }), json!({ "f": "true" }), &["f"], "", ), ( "true vs one", json!({ "f": true }), json!({ "f": 1 }), &["f"], "f/changed/true/1", ), ( "zero vs false", json!({ "f": 0 }), json!({ "f": false }), &["f"], "f/changed/0/false", ), // An empty array is NOT empty (only null and blank text are), so this // is a removal rather than nothing. ( "empty array vs null", json!({ "l": [] }), json!({ "l": null }), &["l"], "l/removed/[]/null", ), ( "empty array vs empty array", json!({ "l": [] }), json!({ "l": [] }), &["l"], "", ), ( "array order matters", json!({ "l": [1, 2] }), json!({ "l": [2, 1] }), &["l"], "l/changed/[1,2]/[2,1]", ), ( "array vs its json text", json!({ "l": [1, 2] }), json!({ "l": "[1,2]" }), &["l"], "l/changed/[1,2]/\"[1,2]\"", ), ( "nested key order", json!({ "meta": { "z": { "b": 1, "a": 2 }, "a": [1, { "d": 4, "c": 3 }] } }), json!({ "meta": { "a": [1, { "c": 3, "d": 4 }], "z": { "a": 2, "b": 1 } } }), &["meta"], "", ), ( "null inside an object is kept, not dropped", json!({ "meta": { "a": null } }), json!({ "meta": {} }), &["meta"], "meta/changed/{\"a\":null}/{}", ), ( "object vs empty string", json!({ "meta": {} }), json!({ "meta": "" }), &["meta"], "meta/removed/{}/\"\"", ), // A body of one NBSP trims to nothing in JavaScript, so it is empty. ( "an NBSP-only body is empty", json!({ "body": "\u{a0}" }), json!({ "body": "" }), &["body"], "", ), ( "a BOM-only body is empty", json!({ "body": "\u{feff}" }), json!({ "body": "" }), &["body"], "", ), // …and a body of one U+0085 is NOT, because ECMAScript's trim leaves it. ( "a NEL-only body is not empty", json!({ "body": "\u{85}" }), json!({ "body": "" }), &["body"], "body/removed/\"\u{85}\"/\"\"", ), ( "a column neither row has", json!({ "a": 1 }), json!({ "a": 1 }), &["nope"], "", ), ( "string vs quoted", json!({ "s": "a" }), json!({ "s": "\"a\"" }), &["s"], "s/changed/\"a\"/\"\\\"a\\\"\"", ), ( "object vs number", json!({ "m": { "a": 1 } }), json!({ "m": 5 }), &["m"], "m/changed/{\"a\":1}/5", ), ( "array vs number", json!({ "m": [1] }), json!({ "m": 1 }), &["m"], "m/changed/[1]/1", ), ( "nested empty object", json!({ "m": { "a": {} } }), json!({ "m": { "a": {} } }), &["m"], "", ), ( "an empty object and an empty array differ", json!({ "m": {} }), json!({ "m": [] }), &["m"], "m/changed/{}/[]", ), ( "astral vs BMP keys sort the same on both sides", json!({ "m": { "\u{1f600}": 1, "\u{ff00}": 2 } }), json!({ "m": { "\u{ff00}": 2, "\u{1f600}": 1 } }), &["m"], "", ), ( "iso instants differ by their precision", json!({ "d": "2026-09-04T10:00:00.000Z" }), json!({ "d": "2026-09-04T10:00:00Z" }), &["d"], "d/changed/\"2026-09-04T10:00:00.000Z\"/\"2026-09-04T10:00:00Z\"", ), ( "negative zero vs zero", json!({ "n": -0.0 }), json!({ "n": 0 }), &["n"], "", ), ( "0.1 + 0.2 spells itself out", json!({ "n": 0.1 + 0.2 }), json!({ "n": "0.30000000000000004" }), &["n"], "", ), ( "1e-7 vs its spelling", json!({ "n": 1e-7 }), json!({ "n": "1e-7" }), &["n"], "", ), ( "a column asked for twice is answered twice", json!({ "a": 1 }), json!({ "a": 2 }), &["a", "a"], "a/changed/1/2 a/changed/1/2", ), ]; for (name, before, after, columns, expected) in vectors { let got = diff_fields(&row(before.clone()), Some(&row(after.clone())), columns); assert_eq!(changes_shape(&got), *expected, "{name}"); } } #[test] fn a_deleted_record_with_a_json_column_reports_both_as_removed() { assert_eq!( changes_shape(&diff_fields( &row(json!({ "meta": { "a": 1 }, "body": "x" })), None, &["meta", "body"], )), "meta/removed/{\"a\":1}/null body/removed/\"x\"/null" ); } // ── shapes ─────────────────────────────────────────────────────────────────── #[test] fn a_word_span_serialises_with_the_typescripts_own_strings() { let json = serde_json::to_string(&WordSpan { kind: WordSpanKind::Removed, text: "x".to_string(), }) .expect("a span serialises"); assert_eq!(json, r#"{"kind":"removed","text":"x"}"#); } #[test] fn a_field_change_serialises_with_the_typescripts_own_keys_in_order() { let json = serde_json::to_string(&FieldChange { column: "title".to_string(), change: FieldChangeKind::Added, before: json!(null), after: json!("Roof"), }) .expect("a change serialises"); assert_eq!( json, r#"{"column":"title","change":"added","before":null,"after":"Roof"}"# ); }