Skip to main content

surjection_core/formats/
mod.rs

1//! Format-preserving editors for native client files (SPEC 7.2).
2//!
3//! A [`Document`] edits one entry at a time inside a container (for example
4//! `mcpServers` in JSON or `mcp_servers` in TOML) and leaves every other byte
5//! alone: comments, key order, indentation, trailing-comma style, a UTF-8 BOM,
6//! CRLF line endings and the final newline survive, and an operation with no
7//! logical change returns the input bytes unchanged.
8//!
9//! Paths are slices of keys from the document root, so keys holding `/` or
10//! `.` (such as project paths in `~/.claude.json`) need no escaping.
11//!
12//! - JSON and JSONC: `jsonc-parser`'s CST. Strict JSON parses without
13//!   comments or trailing commas and never gains them; JSONC accepts both
14//!   (and nothing from JSON5).
15//! - TOML: `toml_edit`. An existing entry is updated key by key inside its
16//!   table, so comments in it survive; tables outside the entry are never
17//!   touched.
18//! - JSON5: a file that also parses as JSONC is edited as JSONC; any other
19//!   JSON5 file is read with the `json5` crate and never written (every
20//!   edit that would change it fails with `read_only_format`).
21//! - YAML: span splice over saphyr's parser (see `yaml.rs`). Entries that
22//!   cannot be located unambiguously (anchors, aliases, flow-style
23//!   containers, several documents) make edits fail with
24//!   `read_only_format`. A last container segment `[field]` addresses a
25//!   sequence of mappings keyed by their `field` member (YAML only; in the
26//!   other formats it is an ordinary key).
27
28mod json5;
29mod jsonc;
30mod text;
31mod toml;
32mod yaml;
33
34use crate::error::{CoreError, ErrorCode};
35
36pub use text::{LineEnding, TextStyle};
37
38/// The syntax of a native client file.
39#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
40#[non_exhaustive]
41pub enum Format {
42    /// Strict JSON (RFC 8259): no comments, no trailing commas.
43    Json,
44    /// JSON with comments and trailing commas.
45    Jsonc,
46    Toml,
47    /// JSON5: read always, written only when the file is also JSONC.
48    Json5,
49    Yaml,
50}
51
52impl Format {
53    pub const fn as_str(self) -> &'static str {
54        match self {
55            Format::Json => "json",
56            Format::Jsonc => "jsonc",
57            Format::Toml => "toml",
58            Format::Json5 => "json5",
59            Format::Yaml => "yaml",
60        }
61    }
62}
63
64/// A format-neutral value read from or written to a native file.
65///
66/// Objects keep their key order (see [`NativeMap`]); equality ignores it,
67/// because neither JSON nor TOML gives key order a meaning.
68#[derive(Debug, Clone, PartialEq)]
69pub enum NativeValue {
70    /// JSON `null`. TOML has none, so writing it to TOML is `invalid_value`.
71    Null,
72    Bool(bool),
73    Integer(i64),
74    /// A finite float. JSON numbers with a fraction or exponent, or outside
75    /// the `i64` range, read as floats.
76    Float(f64),
77    String(String),
78    /// A TOML date-time, in its TOML text form. JSON writes it as a string.
79    Datetime(String),
80    Array(Vec<NativeValue>),
81    Object(NativeMap),
82}
83
84impl NativeValue {
85    /// Parses JSON or JSONC text (one value). Duplicate keys: the first
86    /// wins, as in every [`Document`] operation.
87    pub fn parse_json(text: &str) -> Result<Self, CoreError> {
88        jsonc::parse_value(text)
89    }
90
91    pub fn as_str(&self) -> Option<&str> {
92        match self {
93            NativeValue::String(value) => Some(value),
94            _ => None,
95        }
96    }
97
98    pub fn as_object(&self) -> Option<&NativeMap> {
99        match self {
100            NativeValue::Object(map) => Some(map),
101            _ => None,
102        }
103    }
104
105    pub fn as_array(&self) -> Option<&[NativeValue]> {
106        match self {
107            NativeValue::Array(items) => Some(items),
108            _ => None,
109        }
110    }
111}
112
113impl From<&str> for NativeValue {
114    fn from(value: &str) -> Self {
115        NativeValue::String(value.to_owned())
116    }
117}
118
119impl From<String> for NativeValue {
120    fn from(value: String) -> Self {
121        NativeValue::String(value)
122    }
123}
124
125impl From<bool> for NativeValue {
126    fn from(value: bool) -> Self {
127        NativeValue::Bool(value)
128    }
129}
130
131impl From<i64> for NativeValue {
132    fn from(value: i64) -> Self {
133        NativeValue::Integer(value)
134    }
135}
136
137impl From<NativeMap> for NativeValue {
138    fn from(value: NativeMap) -> Self {
139        NativeValue::Object(value)
140    }
141}
142
143/// Object members in document (or insertion) order, keys unique.
144#[derive(Debug, Clone, Default)]
145pub struct NativeMap {
146    entries: Vec<(String, NativeValue)>,
147}
148
149impl NativeMap {
150    pub fn new() -> Self {
151        Self::default()
152    }
153
154    pub fn len(&self) -> usize {
155        self.entries.len()
156    }
157
158    pub fn is_empty(&self) -> bool {
159        self.entries.is_empty()
160    }
161
162    pub fn get(&self, key: &str) -> Option<&NativeValue> {
163        self.entries
164            .iter()
165            .find(|(name, _)| name == key)
166            .map(|(_, value)| value)
167    }
168
169    pub fn get_mut(&mut self, key: &str) -> Option<&mut NativeValue> {
170        self.entries
171            .iter_mut()
172            .find(|(name, _)| name == key)
173            .map(|(_, value)| value)
174    }
175
176    pub fn contains_key(&self, key: &str) -> bool {
177        self.get(key).is_some()
178    }
179
180    /// Replaces the value of `key` in place, or appends it.
181    pub fn insert(&mut self, key: impl Into<String>, value: NativeValue) -> Option<NativeValue> {
182        let key = key.into();
183        match self.entries.iter_mut().find(|(name, _)| *name == key) {
184            Some((_, slot)) => Some(std::mem::replace(slot, value)),
185            None => {
186                self.entries.push((key, value));
187                None
188            }
189        }
190    }
191
192    pub fn remove(&mut self, key: &str) -> Option<NativeValue> {
193        let index = self.entries.iter().position(|(name, _)| name == key)?;
194        Some(self.entries.remove(index).1)
195    }
196
197    pub fn keys(&self) -> impl Iterator<Item = &str> {
198        self.entries.iter().map(|(name, _)| name.as_str())
199    }
200
201    pub fn iter(&self) -> impl Iterator<Item = (&str, &NativeValue)> {
202        self.entries
203            .iter()
204            .map(|(name, value)| (name.as_str(), value))
205    }
206}
207
208impl PartialEq for NativeMap {
209    fn eq(&self, other: &Self) -> bool {
210        self.len() == other.len()
211            && self
212                .iter()
213                .all(|(key, value)| other.get(key) == Some(value))
214    }
215}
216
217impl<K: Into<String>> FromIterator<(K, NativeValue)> for NativeMap {
218    fn from_iter<I: IntoIterator<Item = (K, NativeValue)>>(iter: I) -> Self {
219        let mut map = NativeMap::new();
220        for (key, value) in iter {
221            map.insert(key, value);
222        }
223        map
224    }
225}
226
227impl IntoIterator for NativeMap {
228    type Item = (String, NativeValue);
229    type IntoIter = std::vec::IntoIter<(String, NativeValue)>;
230
231    fn into_iter(self) -> Self::IntoIter {
232        self.entries.into_iter()
233    }
234}
235
236/// A parsed native file that can be edited without disturbing anything
237/// outside the edited entry.
238///
239/// Containers created by [`Document::upsert`] or [`Document::set_list_member`]
240/// are removed again when a later [`Document::remove`] or
241/// `set_list_member(.., false)` leaves them empty, so an edit that is undone
242/// within one document returns the original bytes. Containers that were in
243/// the file are never removed.
244#[derive(Debug, Clone)]
245pub struct Document {
246    format: Format,
247    style: TextStyle,
248    body: Body,
249    /// Paths of containers this document created, in creation order.
250    created: Vec<Vec<String>>,
251}
252
253#[derive(Debug, Clone)]
254enum Body {
255    Json(jsonc::JsonBody),
256    Toml(toml::TomlBody),
257    Json5(json5::Json5Body),
258    Yaml(yaml::YamlBody),
259}
260
261impl Document {
262    /// Parses a native file. Empty (or whitespace-only) input is an empty
263    /// document, which is how a missing file is edited. Fails with
264    /// `parse_error` when the bytes are not UTF-8 or not valid `format`.
265    pub fn parse(bytes: &[u8], format: Format) -> Result<Self, CoreError> {
266        let (text, style) = text::decode(bytes)?;
267        let body = match format {
268            Format::Json => Body::Json(jsonc::JsonBody::parse(text, true)?),
269            Format::Jsonc => Body::Json(jsonc::JsonBody::parse(text, false)?),
270            Format::Toml => Body::Toml(toml::TomlBody::parse(text)?),
271            Format::Json5 => match jsonc::JsonBody::parse(text.clone(), false) {
272                Ok(body) => Body::Json(body),
273                Err(_) => Body::Json5(json5::Json5Body::parse(text)?),
274            },
275            Format::Yaml => Body::Yaml(yaml::YamlBody::parse(text)?),
276        };
277        Ok(Self {
278            format,
279            style,
280            body,
281            created: Vec::new(),
282        })
283    }
284
285    /// An empty document: the skeleton for a file that does not exist yet.
286    pub fn empty(format: Format) -> Self {
287        Self::parse(b"", format).expect("an empty document parses")
288    }
289
290    pub fn format(&self) -> Format {
291        self.format
292    }
293
294    /// BOM, line endings and final newline detected at parse time and
295    /// restored by [`Document::to_bytes`].
296    pub fn style(&self) -> TextStyle {
297        self.style
298    }
299
300    /// Entry keys of the container at `container`, in document order. A
301    /// missing container has no entries.
302    pub fn list(&self, container: &[&str]) -> Result<Vec<String>, CoreError> {
303        match &self.body {
304            Body::Json(body) => body.list(container),
305            Body::Toml(body) => body.list(container),
306            Body::Json5(body) => body.list(container),
307            Body::Yaml(body) => body.list(container),
308        }
309    }
310
311    /// The value of `key` in the container at `container`.
312    pub fn get(&self, container: &[&str], key: &str) -> Result<Option<NativeValue>, CoreError> {
313        match &self.body {
314            Body::Json(body) => body.get(container, key),
315            Body::Toml(body) => body.get(container, key),
316            Body::Json5(body) => body.get(container, key),
317            Body::Yaml(body) => body.get(container, key),
318        }
319    }
320
321    /// Makes `key` in the container at `container` equal to `value`,
322    /// creating missing containers. A new key is appended at the end of the
323    /// container. An existing key is updated in place: object members that
324    /// keep their value keep their text and comments, members missing from
325    /// `value` are removed and new members are appended. Members the caller
326    /// does not model survive only if `value` carries them (read the entry
327    /// with [`Document::get`] first). Returns whether the document changed;
328    /// on error it is unchanged (`unexpected_shape` for a container that is
329    /// not an object or table, `invalid_value` for a value the format cannot
330    /// hold).
331    pub fn upsert(
332        &mut self,
333        container: &[&str],
334        key: &str,
335        value: &NativeValue,
336    ) -> Result<bool, CoreError> {
337        let mut created = Vec::new();
338        let changed = match &mut self.body {
339            Body::Json(body) => body.upsert(container, key, value, &mut created)?,
340            Body::Toml(body) => body.upsert(container, key, value, &mut created)?,
341            Body::Json5(body) => {
342                if body.get(container, key)?.as_ref() == Some(value) {
343                    false
344                } else {
345                    return Err(body.read_only(container));
346                }
347            }
348            Body::Yaml(body) => body.upsert(container, key, value, &mut created)?,
349        };
350        self.created.extend(created);
351        Ok(changed)
352    }
353
354    /// Removes `key` from the container at `container`, with the comment
355    /// lines directly above it (no blank line between; in JSONC only when
356    /// other members remain; in YAML only those indented like the entry);
357    /// comments above a blank line stay. Returns whether it was there.
358    pub fn remove(&mut self, container: &[&str], key: &str) -> Result<bool, CoreError> {
359        let removed = match &mut self.body {
360            Body::Json(body) => body.remove(container, key)?,
361            Body::Toml(body) => body.remove(container, key)?,
362            Body::Json5(body) => {
363                if body.get(container, key)?.is_some() {
364                    return Err(body.read_only(container));
365                }
366                false
367            }
368            Body::Yaml(body) => body.remove(container, key)?,
369        };
370        if removed {
371            self.prune(container)?;
372        }
373        Ok(removed)
374    }
375
376    /// Adds the string `member` to the array at `list` (creating it) when
377    /// `present`, or removes every occurrence of it otherwise. A new member
378    /// is appended. Returns whether the document changed.
379    pub fn set_list_member(
380        &mut self,
381        list: &[&str],
382        member: &str,
383        present: bool,
384    ) -> Result<bool, CoreError> {
385        if list.is_empty() {
386            return Err(CoreError::new(
387                ErrorCode::InvalidValue,
388                "a list path needs at least one key",
389            ));
390        }
391        let mut created = Vec::new();
392        let changed = match &mut self.body {
393            Body::Json(body) => body.set_list_member(list, member, present, &mut created)?,
394            Body::Toml(body) => body.set_list_member(list, member, present, &mut created)?,
395            Body::Json5(body) => {
396                let (name, parent) = list.split_last().expect("checked above");
397                let listed = body.get(parent, name)?.is_some_and(|value| match value {
398                    NativeValue::Array(items) => {
399                        items.iter().any(|item| item.as_str() == Some(member))
400                    }
401                    _ => false,
402                });
403                if listed != present {
404                    return Err(body.read_only(list));
405                }
406                false
407            }
408            Body::Yaml(body) => body.set_list_member(list, member, present, &mut created)?,
409        };
410        self.created.extend(created);
411        if changed && !present {
412            self.prune(list)?;
413        }
414        Ok(changed)
415    }
416
417    /// The document text with the original BOM, line endings and final
418    /// newline.
419    pub fn to_bytes(&self) -> Vec<u8> {
420        let body = match &self.body {
421            Body::Json(body) => body.text(),
422            Body::Toml(body) => body.text(),
423            Body::Json5(body) => body.text(),
424            Body::Yaml(body) => body.text(),
425        };
426        text::encode(&body, self.style)
427    }
428
429    /// Removes containers this document created that `path` and its
430    /// ancestors left empty, innermost first.
431    fn prune(&mut self, path: &[&str]) -> Result<(), CoreError> {
432        for len in (0..=path.len()).rev() {
433            let prefix = &path[..len];
434            let Some(index) = self.created.iter().position(|created| *created == prefix) else {
435                return Ok(());
436            };
437            let removed = match &mut self.body {
438                Body::Json(body) => body.remove_if_empty(prefix)?,
439                Body::Toml(body) => body.remove_if_empty(prefix)?,
440                Body::Json5(_) => false,
441                Body::Yaml(body) => body.remove_if_empty(prefix)?,
442            };
443            if !removed {
444                return Ok(());
445            }
446            self.created.remove(index);
447        }
448        Ok(())
449    }
450}
451
452/// The mapping keys of a container path: `path` without a last `[field]`
453/// segment (a YAML list keyed by `field`, see the module docs), so the
454/// container is the value at the returned path.
455pub fn mapping_path<'p, 'a>(path: &'p [&'a str]) -> &'p [&'a str] {
456    match path.split_last() {
457        Some((last, rest)) if last.len() > 2 && last.starts_with('[') && last.ends_with(']') => {
458            rest
459        }
460        _ => path,
461    }
462}
463
464/// `unexpected_shape` for the value at `path`.
465fn unexpected_shape(format: Format, path: &[&str], expected: &str) -> CoreError {
466    CoreError::new(
467        ErrorCode::UnexpectedShape,
468        format!(
469            "{} is not {expected}",
470            display_path(format, path.iter().copied())
471        ),
472    )
473}
474
475/// `path` as a JSON pointer (`/a/b`) or a TOML dotted key (`a.b`), for
476/// messages.
477fn display_path<'a>(format: Format, path: impl Iterator<Item = &'a str>) -> String {
478    let path: Vec<&str> = path.collect();
479    match format {
480        Format::Toml if path.is_empty() => "the document root".to_owned(),
481        Format::Toml => path
482            .iter()
483            .map(|key| ::toml_edit::Key::new(*key).display_repr().into_owned())
484            .collect::<Vec<_>>()
485            .join("."),
486        _ if path.is_empty() => "the document root".to_owned(),
487        _ => path
488            .iter()
489            .map(|key| format!("/{}", key.replace('~', "~0").replace('/', "~1")))
490            .collect(),
491    }
492}