Skip to main content

jubarte_edit/edit/
plan.rs

1// SPDX-FileCopyrightText: 2026 Jandira Technologies, LLC
2//
3// SPDX-License-Identifier: Apache-2.0
4
5//! Plan parsing and validation: field checks, operation shapes and
6//! the near-miss field names a refusal suggests.
7
8use super::*;
9
10impl EditPlan {
11    /// Parse and validate a plan's JSON. A field read as another (`anchor`
12    /// as `find`, …) is read without its note: [`Self::from_json_with_notes`]
13    /// returns the notes, and [`apply_plan_json`] puts them in
14    /// `EditReport.notes`.
15    ///
16    /// # Errors
17    ///
18    /// As [`Self::from_json_with_notes`].
19    pub fn from_json(json: &str) -> Result<Self, EditError> {
20        Self::from_json_with_notes(json).map(|(plan, _)| plan)
21    }
22
23    /// Parse and validate a plan's JSON, with a note for each field read
24    /// as another: `anchor` as `find` on `replace`, `delete` and `comment`,
25    /// and `comment` as `text` on `comment` and `reply_comment`.
26    ///
27    /// # Errors
28    ///
29    /// `INVALID_PLAN` when the JSON is malformed or more than one value,
30    /// lacks `schema_version`, or names an unknown field or operation kind:
31    /// the message names the operation, its kind, the fields the kind takes
32    /// and the nearest one. `UNSUPPORTED_SCHEMA` when `schema_version`
33    /// differs from [`SCHEMA_VERSION`].
34    pub fn from_json_with_notes(json: &str) -> Result<(Self, Vec<String>), EditError> {
35        let json = without_byte_order_mark(json);
36        let mut value = plan_value(json)?;
37        let Some(version) = value.get("schema_version") else {
38            return Err(err(
39                "INVALID_PLAN",
40                None,
41                format!("schema_version is required ({SCHEMA_VERSION} for this build)"),
42            ));
43        };
44        if let Some(version) = version.as_u64().filter(|v| *v != u64::from(SCHEMA_VERSION)) {
45            return Err(err(
46                "UNSUPPORTED_SCHEMA",
47                None,
48                format!("schema_version {version} is not supported (expected {SCHEMA_VERSION})"),
49            ));
50        }
51        check_plan_keys(&value)?;
52        check_change_filters(&value)?;
53        let notes = check_operations(&mut value)?;
54        // Each operation is read on its own, so its error names it.
55        let operations = match value.get_mut("operations") {
56            Some(serde_json::Value::Array(operations)) => std::mem::take(operations),
57            _ => Vec::new(),
58        };
59        let mut plan: Self =
60            serde_json::from_value(value).map_err(|e| err("INVALID_PLAN", None, e.to_string()))?;
61        plan.operations = operations
62            .into_iter()
63            .enumerate()
64            .map(|(i, op)| {
65                let label = operation_label(i, &op);
66                let kind = op["kind"].as_str().unwrap_or_default().to_string();
67                serde_json::from_value(op)
68                    .map_err(|e| err("INVALID_PLAN", Some(label.as_str()), format!("{kind}: {e}")))
69            })
70            .collect::<Result<_, _>>()?;
71        Ok((plan, notes))
72    }
73
74    /// Serialize the plan.
75    pub fn to_json(&self) -> String {
76        serde_json::to_string_pretty(self).expect("plan serializes")
77    }
78}
79
80pub(super) fn at_least_one(fields: &[&str]) -> serde_json::Value {
81    serde_json::json!(
82        fields
83            .iter()
84            .map(|field| serde_json::json!({"required": [field]}))
85            .collect::<Vec<_>>()
86    )
87}
88
89pub(super) fn exactly_one(fields: &[&str]) -> serde_json::Value {
90    // Each alternative requires one field and excludes every other field.
91    serde_json::json!(
92        fields
93            .iter()
94            .map(|field| serde_json::json!({
95                "required": [field],
96                "not": {"anyOf": fields.iter().filter(|other| *other != field)
97                    .map(|other| serde_json::json!({"required": [other]})).collect::<Vec<_>>()}
98            }))
99            .collect::<Vec<_>>()
100    )
101}
102
103/// The top-level fields of a plan, as [`EditPlan`] reads them.
104pub(super) const PLAN_FIELDS: &[&str] = &[
105    "author",
106    "date",
107    "existing_revisions",
108    "initials",
109    "operations",
110    "others",
111    "removed_anchor_comments",
112    "resolve_revisions",
113    "rewrite_others_comments",
114    "schema_version",
115    "source_sha256",
116    "update_fields",
117];
118
119/// A field one kind's operations take under another name, read as meant
120/// with a note: (written, read as, kinds).
121const ALIASES: &[(&str, &str, &[&str])] = &[
122    ("comment", "text", &["comment", "reply_comment"]),
123    ("anchor", "find", &["replace", "delete", "comment"]),
124];
125
126/// `json` without a leading byte order mark, which RFC 8259 (§8.1) lets a
127/// parser ignore: editors that save UTF-8 with one write it first.
128pub(super) fn without_byte_order_mark(json: &str) -> &str {
129    json.strip_prefix('\u{feff}').unwrap_or(json)
130}
131
132/// The plan's JSON: one value, an object, with nothing after it.
133fn plan_value(json: &str) -> Result<serde_json::Value, EditError> {
134    let value: serde_json::Value = serde_json::from_str(json).map_err(|e| {
135        // One whole value parses: what the parser refused follows it.
136        let whole = serde_json::Deserializer::from_str(json)
137            .into_iter::<serde::de::IgnoredAny>()
138            .next()
139            .is_some_and(|first| first.is_ok());
140        let message = if whole {
141            format!(
142                "the plan must be exactly one JSON object; characters follow it at line {} column {}",
143                e.line(),
144                e.column()
145            )
146        } else {
147            e.to_string()
148        };
149        err("INVALID_PLAN", None, message)
150    })?;
151    if !value.is_object() {
152        return Err(err(
153            "INVALID_PLAN",
154            None,
155            format!(
156                "the plan must be exactly one JSON object, not {}",
157                json_kind(&value)
158            ),
159        ));
160    }
161    Ok(value)
162}
163
164/// What a JSON value is, for a message.
165fn json_kind(value: &serde_json::Value) -> &'static str {
166    match value {
167        serde_json::Value::Null => "null",
168        serde_json::Value::Bool(_) => "a boolean",
169        serde_json::Value::Number(_) => "a number",
170        serde_json::Value::String(_) => "a string",
171        serde_json::Value::Array(_) => "an array",
172        serde_json::Value::Object(_) => "an object",
173    }
174}
175
176/// The name an error gives operation `i`: its `id`, else `op-N` as the
177/// report names it.
178fn operation_label(i: usize, op: &serde_json::Value) -> String {
179    op.get("id")
180        .and_then(serde_json::Value::as_str)
181        .map_or_else(|| format!("op-{}", i + 1), str::to_string)
182}
183
184/// The plan's own fields: an unknown one names the fields and the nearest.
185fn check_plan_keys(plan: &serde_json::Value) -> Result<(), EditError> {
186    let map = plan.as_object().expect("plan_value checked an object");
187    match map.keys().find(|key| !PLAN_FIELDS.contains(&key.as_str())) {
188        Some(key) => Err(err(
189            "INVALID_PLAN",
190            None,
191            unknown_field(key, PLAN_FIELDS, None),
192        )),
193        None => Ok(()),
194    }
195}
196
197/// `unknown field "key"; did you mean "nearest"? fields: …`.
198pub(super) fn unknown_field(key: &str, fields: &[&str], meant: Option<&str>) -> String {
199    let hint = nearest(key, fields, meant)
200        .map(|name| format!("did you mean {name:?}? "))
201        .unwrap_or_default();
202    format!("unknown field {key:?}; {hint}fields: {}", fields.join(", "))
203}
204
205/// `resolve_revisions.accept.ids` (and `authors`, `kinds`) are arrays; a
206/// single string is the slip worth naming.
207fn check_change_filters(plan: &serde_json::Value) -> Result<(), EditError> {
208    for side in ["accept", "reject"] {
209        for key in ["ids", "authors", "kinds"] {
210            if let Some(one) = plan
211                .pointer(&format!("/resolve_revisions/{side}/{key}"))
212                .and_then(serde_json::Value::as_str)
213            {
214                return Err(err(
215                    "INVALID_PLAN",
216                    None,
217                    format!(
218                        "resolve_revisions.{side}.{key} is an array: write {}",
219                        serde_json::json!([one])
220                    ),
221                ));
222            }
223        }
224    }
225    Ok(())
226}
227
228/// Each operation's fields against its kind's schema (the table
229/// `capabilities` lists): an error names the operation, its kind, the
230/// fields the kind takes and the nearest one. Serde's `flatten` cannot
231/// deny unknown fields itself, and a misspelled key must not silently
232/// change meaning. The [`ALIASES`] are read as meant, each with a note,
233/// and a failed plan's `why` is dropped: a note for whoever fixes it.
234fn check_operations(plan: &mut serde_json::Value) -> Result<Vec<String>, EditError> {
235    const COMMON: &[&str] = &["id", "kind", "group", "why"];
236    let mut notes = Vec::new();
237    let Some(ops) = plan
238        .get_mut("operations")
239        .and_then(serde_json::Value::as_array_mut)
240    else {
241        return Ok(notes);
242    };
243    let kinds = dispatched_operation_kinds();
244    let kind_names: Vec<&str> = kinds.iter().map(String::as_str).collect();
245    for (i, op) in ops.iter_mut().enumerate() {
246        let label = operation_label(i, op);
247        let invalid = |message: String| err("INVALID_PLAN", Some(label.as_str()), message);
248        let what = json_kind(op);
249        let Some(map) = op.as_object_mut() else {
250            return Err(invalid(format!(
251                "an operation is a JSON object, not {what}"
252            )));
253        };
254        match map.get("id") {
255            Some(serde_json::Value::Number(n)) => {
256                return Err(invalid(format!(
257                    "id is a string, not a number: write \"{n}\""
258                )));
259            }
260            Some(id) if !id.is_string() => {
261                return Err(invalid(format!("id is a string, not {}", json_kind(id))));
262            }
263            _ => {}
264        }
265        let kind = match map.get("kind") {
266            Some(serde_json::Value::String(kind)) => kind.clone(),
267            None => {
268                return Err(invalid(format!(
269                    "kind is required; kinds: {}",
270                    kinds.join(", ")
271                )));
272            }
273            Some(other) => {
274                return Err(invalid(format!(
275                    "kind is a string, not {}; kinds: {}",
276                    json_kind(other),
277                    kinds.join(", ")
278                )));
279            }
280        };
281        let Some(schema) = operation_schemas()
282            .iter()
283            .find(|schema| schema["properties"]["kind"]["const"] == kind.as_str())
284        else {
285            let hint = nearest(&kind, &kind_names, None)
286                .map(|name| format!("did you mean {name:?}? "))
287                .unwrap_or_default();
288            return Err(invalid(format!(
289                "unknown kind {kind:?}; {hint}kinds: {}",
290                kinds.join(", ")
291            )));
292        };
293        for (written, read, takes) in ALIASES {
294            if takes.contains(&kind.as_str())
295                && !map.contains_key(*read)
296                && let Some(value) = map.remove(*written)
297            {
298                map.insert((*read).to_string(), value);
299                notes.push(format!(
300                    "{label} ({kind}): field {written:?} is read as {read:?}"
301                ));
302            }
303        }
304        let refusal = match kind.as_str() {
305            "list" => Some("takes paragraphs, not paragraph"),
306            "watermark" => Some("a watermark takes no paragraph"),
307            "settings" => Some("settings take no paragraph"),
308            "fill_control" => Some("selects a control, not a paragraph"),
309            "page_setup" => Some("sections take no paragraph"),
310            _ => None,
311        };
312        if let Some(message) = refusal.filter(|_| map.contains_key("paragraph")) {
313            return Err(invalid(format!("{kind}: {message}")));
314        }
315        let allowed = schema["properties"]
316            .as_object()
317            .expect("operation properties");
318        let fields: Vec<&str> = allowed
319            .keys()
320            .map(String::as_str)
321            .filter(|field| !COMMON.contains(field))
322            .collect();
323        if let Some(key) = map
324            .keys()
325            .find(|key| !COMMON.contains(&key.as_str()) && !allowed.contains_key(*key))
326        {
327            if let Some((_, read, _)) = ALIASES.iter().find(|(written, read, takes)| {
328                written == key && takes.contains(&kind.as_str()) && map.contains_key(*read)
329            }) {
330                return Err(invalid(format!(
331                    "{kind}: {key:?} is read as {read:?}, which the operation gives too: drop one"
332                )));
333            }
334            // A name the operation already gives is no suggestion.
335            let absent: Vec<&str> = fields
336                .iter()
337                .copied()
338                .filter(|field| !map.contains_key(*field))
339                .collect();
340            let hint = nearest(key, &absent, meant_field(&kind, key))
341                .map(|name| format!("did you mean {name:?}? "))
342                .unwrap_or_default();
343            return Err(invalid(format!(
344                "{kind}: unknown field {key:?}; {hint}fields: {}",
345                fields.join(", ")
346            )));
347        }
348        for key in ["paragraph", "like", "through"] {
349            if let Some(n) = map.get(key).filter(|v| v.is_number()) {
350                return Err(invalid(format!(
351                    "{kind}: {key} is a selector, not a number: write {}",
352                    index_selector(n)
353                )));
354            }
355        }
356        if let Some(n) = map
357            .get("paragraphs")
358            .and_then(serde_json::Value::as_array)
359            .and_then(|list| list.iter().find(|v| v.is_number()))
360        {
361            return Err(invalid(format!(
362                "{kind}: paragraphs holds selectors, not numbers: write {}",
363                index_selector(n)
364            )));
365        }
366        map.remove("why");
367    }
368    Ok(notes)
369}
370
371/// The selector a bare paragraph number meant: `{"index": n}` for a whole
372/// number from 0, else what an index is.
373fn index_selector(n: &serde_json::Value) -> String {
374    n.as_u64().map_or_else(
375        || r#"{"index": N}, N a whole number from 0"#.to_string(),
376        |n| format!(r#"{{"index": {n}}}"#),
377    )
378}
379
380/// The field a plan gives another one's name: `text` for a replacement,
381/// `comment` for a comment's text, `anchor` for `find`.
382/// `text` on `replace` is no alias, only a hint: `text` is what `insert`
383/// and `rewrite` take, so the slip is named rather than read.
384fn meant_field(kind: &str, key: &str) -> Option<&'static str> {
385    match (kind, key) {
386        ("replace", "text") => Some("replacement"),
387        (_, "comment") => Some("text"),
388        (_, "anchor") => Some("find"),
389        _ => None,
390    }
391}
392
393/// The name a slip most likely meant: `meant` when it is one of `names`,
394/// else the closest by edit distance within a third of the slip's length.
395pub(super) fn nearest<'a>(key: &str, names: &[&'a str], meant: Option<&str>) -> Option<&'a str> {
396    if let Some(name) = meant.and_then(|m| names.iter().copied().find(|name| *name == m)) {
397        return Some(name);
398    }
399    let limit = (key.chars().count() / 3).max(1);
400    names
401        .iter()
402        .map(|name| (edit_distance(key, name), *name))
403        .filter(|(distance, _)| *distance <= limit)
404        .min_by_key(|(distance, _)| *distance)
405        .map(|(_, name)| name)
406}
407
408/// Levenshtein distance between two names, by characters.
409pub(super) fn edit_distance(a: &str, b: &str) -> usize {
410    let b: Vec<char> = b.chars().collect();
411    let mut row: Vec<usize> = (0..=b.len()).collect();
412    for (i, ca) in a.chars().enumerate() {
413        let mut diagonal = row[0];
414        row[0] = i + 1;
415        for (j, cb) in b.iter().enumerate() {
416            let above = row[j + 1];
417            row[j + 1] = (above + 1)
418                .min(row[j] + 1)
419                .min(diagonal + usize::from(ca != *cb));
420            diagonal = above;
421        }
422    }
423    row[b.len()]
424}