surjection-core 1.2.0

Core library of Surjection: MCP servers, skills and secret references for AI coding clients
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
//! JSON and JSONC editing through `jsonc-parser`'s CST.
//!
//! The body is kept as text. The CST is `Rc`-based, so it cannot live in a
//! `Send` document; what can is a tree of the values the text holds
//! ([`Node`]), built from the parse that checks the text and again after
//! each change, on the next read. Reads (`list`, `get`) go through it, so
//! reading every entry of a file costs one parse, however many entries it
//! holds (#14). Clones share it until one of them changes its text.
//!
//! An edit parses the text once and works on that CST; a step that follows
//! a change parses the new text again, so every step sees the CST a parse
//! of the current text gives, as when each step parsed on its own. An
//! operation that changes nothing never re-serializes, so its output is the
//! input, and a failed operation restores the text it started from.
//!
//! The CST lays out new values on several lines, indented like the file.
//! Inside a one-line object (`{"a": 1}`, or anything in a one-line file) it
//! would also break the object over several lines, so members are added and
//! values replaced there by splicing one-line text that copies the object's
//! own `:` and `,` spacing.

use std::sync::{Arc, OnceLock};

use jsonc_parser::cst::{
    CstContainerNode, CstInputValue, CstLeafNode, CstNode, CstObject, CstObjectProp, CstRootNode,
};
use jsonc_parser::{CollectOptions, ParseOptions};

use super::{Format, NativeMap, NativeValue, unexpected_shape};
use crate::error::{CoreError, ErrorCode};

#[derive(Debug, Clone)]
pub(super) struct JsonBody {
    text: String,
    strict: bool,
    /// The original text when it held no value (an empty or new file). Once
    /// the root object this document created is empty again, the text goes
    /// back to it.
    blank: Option<String>,
    /// The value `text` holds (`None` for no value), built on the first
    /// read after a change ([`JsonBody::set_text`] replaces it).
    values: Arc<OnceLock<Result<Option<Node>, CoreError>>>,
}

/// A value of the text as reads see it. An object keeps every member whose
/// name decodes, in file order and with duplicates, as the CST lists them;
/// a lookup takes the first one, as `CstObject::get` does.
#[derive(Debug, Clone)]
enum Node {
    Object(Vec<(String, Node)>),
    Value(NativeValue),
}

impl Node {
    fn of(node: &CstNode) -> Self {
        match node {
            CstNode::Container(CstContainerNode::Object(object)) => Node::Object(
                object
                    .properties()
                    .iter()
                    .filter_map(|prop| {
                        let name = prop.decoded_name()?;
                        let value = prop
                            .value()
                            .map_or(Node::Value(NativeValue::Null), |node| Node::of(&node));
                        Some((name, value))
                    })
                    .collect(),
            ),
            other => Node::Value(to_native(other)),
        }
    }

    /// [`to_native`] of the CST node this was built from.
    fn to_native(&self) -> NativeValue {
        match self {
            Node::Object(members) => {
                let mut map = NativeMap::new();
                for (name, value) in members {
                    if !map.contains_key(name) {
                        map.insert(name.clone(), value.to_native());
                    }
                }
                NativeValue::Object(map)
            }
            Node::Value(value) => value.clone(),
        }
    }

    /// The value of the first member named `key`.
    fn member<'n>(members: &'n [(String, Node)], key: &str) -> Option<&'n Self> {
        members
            .iter()
            .find(|(name, _)| name == key)
            .map(|(_, value)| value)
    }
}

impl JsonBody {
    pub(super) fn parse(text: String, strict: bool) -> Result<Self, CoreError> {
        if strict {
            // The CST parser keeps comments as tokens whatever the options
            // say; the AST parser enforces `allow_comments`.
            jsonc_parser::parse_to_ast(&text, &CollectOptions::default(), &options(true))
                .map_err(|err| parse_error(strict, &err))?;
        }
        let root = parse(&text, strict)?;
        let value = root.value();
        let blank = value.is_none().then(|| text.clone());
        let values = Arc::new(OnceLock::from(Ok(value.as_ref().map(Node::of))));
        Ok(Self {
            text,
            strict,
            blank,
            values,
        })
    }

    pub(super) fn text(&self) -> String {
        self.text.clone()
    }

    /// Sets the text; the values are built again on the next read.
    fn set_text(&mut self, text: String) {
        self.text = text;
        self.values = Arc::default();
    }

    fn format(&self) -> Format {
        if self.strict {
            Format::Json
        } else {
            Format::Jsonc
        }
    }

    /// The CST of the current text, which this module only ever sets to
    /// valid JSON(C).
    fn root(&self) -> Result<CstRootNode, CoreError> {
        parse(&self.text, self.strict)
    }

    /// The value the current text holds.
    fn values(&self) -> Result<Option<&Node>, CoreError> {
        self.values
            .get_or_init(|| Ok(self.root()?.value().as_ref().map(Node::of)))
            .as_ref()
            .map(Option::as_ref)
            .map_err(Clone::clone)
    }

    /// The members of the object at `path` ([`JsonBody::object_at`] over
    /// the values).
    fn members_at(&self, path: &[&str]) -> Result<Option<&[(String, Node)]>, CoreError> {
        let Some(value) = self.values()? else {
            return Ok(None);
        };
        let Node::Object(root) = value else {
            return Err(unexpected_shape(self.format(), &[], "an object"));
        };
        let mut members: &[(String, Node)] = root;
        for (depth, key) in path.iter().enumerate() {
            let Some(value) = Node::member(members, key) else {
                return Ok(None);
            };
            let Node::Object(inner) = value else {
                return Err(unexpected_shape(
                    self.format(),
                    &path[..=depth],
                    "an object",
                ));
            };
            members = inner;
        }
        Ok(Some(members))
    }

    pub(super) fn list(&self, container: &[&str]) -> Result<Vec<String>, CoreError> {
        let Some(members) = self.members_at(container)? else {
            return Ok(Vec::new());
        };
        Ok(members.iter().map(|(name, _)| name.clone()).collect())
    }

    pub(super) fn get(
        &self,
        container: &[&str],
        key: &str,
    ) -> Result<Option<NativeValue>, CoreError> {
        let Some(members) = self.members_at(container)? else {
            return Ok(None);
        };
        Ok(Node::member(members, key).map(Node::to_native))
    }

    pub(super) fn upsert(
        &mut self,
        container: &[&str],
        key: &str,
        value: &NativeValue,
        created: &mut Vec<Vec<String>>,
    ) -> Result<bool, CoreError> {
        check_finite(value)?;
        let root = self.root()?;
        let current = self.object_at(&root, container)?.and_then(|object| {
            object.get(key).map(|prop| {
                prop.value()
                    .map_or(NativeValue::Null, |node| to_native(&node))
            })
        });
        if current.as_ref() == Some(value) {
            return Ok(false);
        }
        self.atomic(|body| {
            let root = body.ensure_object(root, container, created)?;
            match current {
                Some(_) => body.merge(root, container, key, value).map(drop),
                None => body.append(root, container, key, value),
            }
        })?;
        Ok(true)
    }

    pub(super) fn remove(&mut self, container: &[&str], key: &str) -> Result<bool, CoreError> {
        let root = self.root()?;
        let Some(prop) = self
            .object_at(&root, container)?
            .and_then(|object| object.get(key))
        else {
            return Ok(false);
        };
        remove_member(prop.into());
        self.set_text(root.to_string());
        Ok(true)
    }

    pub(super) fn set_list_member(
        &mut self,
        list: &[&str],
        member: &str,
        present: bool,
        created: &mut Vec<Vec<String>>,
    ) -> Result<bool, CoreError> {
        let (name, parent) = list.split_last().expect("checked by Document");
        let root = self.root()?;
        let current = match self.object_at(&root, parent)? {
            Some(object) => object.get(name),
            None => None,
        };
        let Some(prop) = current else {
            if !present {
                return Ok(false);
            }
            let array = NativeValue::Array(vec![NativeValue::from(member)]);
            self.atomic(|body| {
                let root = body.ensure_object(root, parent, created)?;
                body.append(root, parent, name, &array)
            })?;
            created.push(owned(list));
            return Ok(true);
        };
        let array = prop
            .value()
            .and_then(|node| node.as_array())
            .ok_or_else(|| unexpected_shape(self.format(), list, "an array"))?;
        let hits: Vec<CstNode> = array
            .elements()
            .into_iter()
            .filter(|node| to_native(node).as_str() == Some(member))
            .collect();
        if present == !hits.is_empty() {
            return Ok(false);
        }
        if present {
            array.append(CstInputValue::String(member.to_owned()));
        } else {
            for node in hits {
                remove_member(node);
            }
        }
        self.set_text(root.to_string());
        Ok(true)
    }

    /// Removes the object or array at `path` when it is empty. The root
    /// object is "removed" by restoring the blank original text.
    pub(super) fn remove_if_empty(&mut self, path: &[&str]) -> Result<bool, CoreError> {
        let root = self.root()?;
        let Some((name, parent)) = path.split_last() else {
            let empty = root
                .object_value()
                .is_some_and(|object| object.properties().is_empty());
            return Ok(match (&self.blank, empty) {
                (Some(blank), true) => {
                    self.set_text(blank.clone());
                    true
                }
                _ => false,
            });
        };
        let Some(prop) = self
            .object_at(&root, parent)?
            .and_then(|object| object.get(name))
        else {
            return Ok(false);
        };
        let empty = match prop.value() {
            Some(CstNode::Container(CstContainerNode::Object(object))) => {
                object.properties().is_empty()
            }
            Some(CstNode::Container(CstContainerNode::Array(array))) => array.elements().is_empty(),
            _ => false,
        };
        if empty {
            remove_member(prop.into());
            self.set_text(root.to_string());
        }
        Ok(empty)
    }

    /// Runs `steps`; on failure the text goes back to what it was.
    fn atomic(
        &mut self,
        steps: impl FnOnce(&mut Self) -> Result<(), CoreError>,
    ) -> Result<(), CoreError> {
        let saved = (self.text.clone(), self.values.clone());
        let result = steps(self);
        if result.is_err() {
            (self.text, self.values) = saved;
        }
        result
    }

    /// Creates the root object and the objects on `path` that are missing.
    /// `root` is the CST of the current text; returns the CST of the text
    /// after (parsed again when something was created).
    fn ensure_object(
        &mut self,
        mut root: CstRootNode,
        path: &[&str],
        created: &mut Vec<Vec<String>>,
    ) -> Result<CstRootNode, CoreError> {
        if root.value().is_none() {
            root.object_value_or_set();
            self.set_text(root.to_string());
            created.push(Vec::new());
            root = self.root()?;
        }
        for depth in 0..path.len() {
            if self.object_at(&root, &path[..=depth])?.is_none() {
                self.append(
                    root,
                    &path[..depth],
                    path[depth],
                    &NativeValue::Object(NativeMap::new()),
                )?;
                created.push(owned(&path[..=depth]));
                root = self.root()?;
            }
        }
        Ok(root)
    }

    /// Makes `key` in the object at `parent` equal to `new`, keeping the text
    /// of every member whose value already is. `root` is the CST of the
    /// current text. Returns whether the text changed.
    fn merge(
        &mut self,
        root: CstRootNode,
        parent: &[&str],
        key: &str,
        new: &NativeValue,
    ) -> Result<bool, CoreError> {
        let prop = self.prop_at(&root, parent, key)?;
        let old = prop.value();
        if old.as_ref().map(to_native).as_ref() == Some(new) {
            return Ok(false);
        }
        let (Some(object), NativeValue::Object(map)) = (old.and_then(|node| node.as_object()), new)
        else {
            self.replace(root, parent, key, new)?;
            return Ok(true);
        };
        let stale: Vec<CstObjectProp> = object
            .properties()
            .into_iter()
            .filter(|prop| {
                prop.decoded_name()
                    .is_some_and(|name| !map.contains_key(&name))
            })
            .collect();
        let mut root = root;
        if !stale.is_empty() {
            for prop in stale {
                remove_member(prop.into());
            }
            self.set_text(root.to_string());
            root = self.root()?;
        }
        let mut path = parent.to_vec();
        path.push(key);
        for (member, value) in map.iter() {
            let exists = self
                .object_at(&root, &path)?
                .is_some_and(|object| object.get(member).is_some());
            let changed = if exists {
                self.merge(root.clone(), &path, member, value)?
            } else {
                self.append(root.clone(), &path, member, value)?;
                true
            };
            if changed {
                root = self.root()?;
            }
        }
        Ok(true)
    }

    /// Appends `key: value` to the object at `path`; `root` is the CST of
    /// the current text.
    fn append(
        &mut self,
        root: CstRootNode,
        path: &[&str],
        key: &str,
        value: &NativeValue,
    ) -> Result<(), CoreError> {
        let object = self
            .object_at(&root, path)?
            .expect("the caller checked the object exists");
        if !one_line(&root, &object) {
            object.append(key, to_input(value));
            self.set_text(root.to_string());
            return Ok(());
        }
        let spacing = Spacing::of(&root, &object);
        let member = format!(
            "{}{}{}",
            json_string(key),
            spacing.colon,
            spacing.render(value)
        );
        let (at, insert) = match object.properties().last() {
            Some(last) => (
                end_offset(&last.clone().into()),
                format!("{}{member}", spacing.comma),
            ),
            // Just after `{`.
            None => (start_offset(&object.clone().into()) + 1, member),
        };
        let mut text = root.to_string();
        text.insert_str(at, &insert);
        self.set_text(text);
        Ok(())
    }

    /// Replaces the value of `key` in the object at `parent`; `root` is the
    /// CST of the current text.
    fn replace(
        &mut self,
        root: CstRootNode,
        parent: &[&str],
        key: &str,
        value: &NativeValue,
    ) -> Result<(), CoreError> {
        let object = self
            .object_at(&root, parent)?
            .expect("the caller checked the object exists");
        let prop = object
            .get(key)
            .expect("the caller checked the member exists");
        match prop.value() {
            Some(old) if one_line(&root, &object) => {
                let start = start_offset(&old);
                let end = start + old.to_string().len();
                let mut text = root.to_string();
                text.replace_range(start..end, &Spacing::of(&root, &object).render(value));
                self.set_text(text);
            }
            _ => {
                prop.set_value(to_input(value));
                self.set_text(root.to_string());
            }
        }
        Ok(())
    }

    fn prop_at(
        &self,
        root: &CstRootNode,
        parent: &[&str],
        key: &str,
    ) -> Result<CstObjectProp, CoreError> {
        Ok(self
            .object_at(root, parent)?
            .and_then(|object| object.get(key))
            .expect("the caller checked the member exists"))
    }

    fn object_at(&self, root: &CstRootNode, path: &[&str]) -> Result<Option<CstObject>, CoreError> {
        let Some(value) = root.value() else {
            return Ok(None);
        };
        let mut object = value
            .as_object()
            .ok_or_else(|| unexpected_shape(self.format(), &[], "an object"))?;
        for (depth, key) in path.iter().enumerate() {
            let Some(prop) = object.get(key) else {
                return Ok(None);
            };
            object = prop
                .value()
                .and_then(|node| node.as_object())
                .ok_or_else(|| unexpected_shape(self.format(), &path[..=depth], "an object"))?;
        }
        Ok(Some(object))
    }
}

fn parse(text: &str, strict: bool) -> Result<CstRootNode, CoreError> {
    CstRootNode::parse(text, &options(strict)).map_err(|err| parse_error(strict, &err))
}

fn parse_error(strict: bool, err: &jsonc_parser::errors::ParseError) -> CoreError {
    let kind = if strict { "JSON" } else { "JSONC" };
    CoreError::new(ErrorCode::ParseError, format!("invalid {kind}: {err}"))
}

/// Strict JSON, or JSON plus comments and trailing commas. The JSON5
/// extensions `jsonc-parser` also knows stay off, so a JSON5 file never
/// passes as JSONC.
fn options(strict: bool) -> ParseOptions {
    ParseOptions {
        allow_comments: !strict,
        allow_trailing_commas: !strict,
        allow_loose_object_property_names: false,
        allow_missing_commas: false,
        allow_single_quoted_strings: false,
        allow_hexadecimal_numbers: false,
        allow_unary_plus_numbers: false,
        allow_bare_decimal_point_numbers: false,
        allow_non_finite_numbers: false,
        allow_extended_string_escapes: false,
    }
}

pub(super) fn parse_value(text: &str) -> Result<NativeValue, CoreError> {
    let root = parse(text, false)?;
    root.value()
        .map(|node| to_native(&node))
        .ok_or_else(|| CoreError::new(ErrorCode::ParseError, "invalid JSON: no value"))
}

/// Whether new text in `object` belongs on one line: the object is on one
/// line and has members, or it is empty and the whole file is one line.
fn one_line(root: &CstRootNode, object: &CstObject) -> bool {
    if object.to_string().contains('\n') {
        return false;
    }
    if !object.properties().is_empty() {
        return true;
    }
    root.object_value()
        .is_some_and(|root| !root.properties().is_empty() && !root.to_string().contains('\n'))
}

/// The `:` and `,` spacing of a one-line object.
struct Spacing {
    colon: String,
    comma: String,
}

impl Spacing {
    /// Copied from `object`, or from the root object when that is on one
    /// line too; otherwise `": "` and `", "`.
    fn of(root: &CstRootNode, object: &CstObject) -> Self {
        let samples: Vec<CstObject> = std::iter::once(object.clone())
            .chain(
                root.object_value()
                    .filter(|root| !root.to_string().contains('\n')),
            )
            .collect();
        let colon = samples
            .iter()
            .flat_map(CstObject::properties)
            .find_map(|prop| colon_of(&prop))
            .unwrap_or_else(|| ": ".to_owned());
        let comma = samples
            .iter()
            .find_map(comma_of)
            .unwrap_or_else(|| if colon.ends_with(' ') { ", " } else { "," }.to_owned());
        Self { colon, comma }
    }

    /// `value` as one-line JSON with this spacing.
    fn render(&self, value: &NativeValue) -> String {
        match value {
            NativeValue::Array(items) => {
                let items: Vec<String> = items.iter().map(|item| self.render(item)).collect();
                format!("[{}]", items.join(&self.comma))
            }
            NativeValue::Object(map) => {
                let members: Vec<String> = map
                    .iter()
                    .map(|(key, value)| {
                        format!("{}{}{}", json_string(key), self.colon, self.render(value))
                    })
                    .collect();
                format!("{{{}}}", members.join(&self.comma))
            }
            scalar => match to_input(scalar) {
                CstInputValue::Null => "null".to_owned(),
                CstInputValue::Bool(value) => value.to_string(),
                CstInputValue::Number(text) => text,
                CstInputValue::String(text) => json_string(&text),
                CstInputValue::Array(_) | CstInputValue::Object(_) => unreachable!("scalar"),
            },
        }
    }
}

/// The text between a member's name and its value (`:`, `: `).
fn colon_of(prop: &CstObjectProp) -> Option<String> {
    let children = prop.children();
    let name = children
        .iter()
        .position(|node| node.as_string_lit().is_some())?;
    let value = prop.value()?.child_index();
    Some(
        children[name + 1..value]
            .iter()
            .map(ToString::to_string)
            .collect(),
    )
}

/// The text between the first two members of `object` (`,`, `, `).
fn comma_of(object: &CstObject) -> Option<String> {
    let props = object.properties();
    let (first, second) = (props.first()?, props.get(1)?);
    let children = object.children();
    Some(
        children[first.child_index() + 1..second.child_index()]
            .iter()
            .map(ToString::to_string)
            .collect(),
    )
}

/// Removes an object member or array element. A member takes with it the
/// own-line comments directly above it (no blank line between), as a TOML
/// table does, unless it is the only member: a member added to an object
/// that holds only comments goes below them, and removing it again must
/// leave them. Removing the first item of a one-line `[a, b]` or `{...}`
/// leaves no space after the bracket.
fn remove_member(node: CstNode) {
    let parent = node.parent();
    let gap = |parent: &CstContainerNode| parent.child_at_index(1).filter(CstNode::is_whitespace);
    let had_gap = parent.as_ref().map(|parent| gap(parent).is_some());
    if let Some(object) = parent.as_ref().and_then(CstContainerNode::as_object)
        && object.properties().len() > 1
    {
        for comment in attached_comments(&node) {
            if !comment.is_line_comment() {
                // Do what removing a line comment does: its indentation and
                // the line break before it go too.
                for previous in comment.previous_siblings() {
                    let newline = previous.is_newline();
                    if !newline && !previous.is_whitespace() {
                        break;
                    }
                    previous.remove();
                    if newline {
                        break;
                    }
                }
            }
            comment.remove();
        }
    }
    node.remove();
    if let (Some(parent), Some(false)) = (parent, had_gap)
        && !parent.to_string().contains('\n')
        && let Some(space) = gap(&parent)
    {
        space.remove();
    }
}

/// Own-line comments directly above `node`, nearest first.
fn attached_comments(node: &CstNode) -> Vec<jsonc_parser::cst::CstComment> {
    let previous: Vec<CstNode> = node.previous_siblings().collect();
    let skip_space = |mut index: usize| {
        while previous.get(index).is_some_and(CstNode::is_whitespace) {
            index += 1;
        }
        index
    };
    let mut comments = Vec::new();
    let mut index = skip_space(0);
    while previous.get(index).is_some_and(CstNode::is_newline) {
        let at = skip_space(index + 1);
        let Some(comment) = previous.get(at).and_then(CstNode::as_comment) else {
            break;
        };
        let before = skip_space(at + 1);
        // A comment after `{`, `,` or a value on its line is not own-line.
        if !previous.get(before).is_some_and(CstNode::is_newline) {
            break;
        }
        comments.push(comment);
        index = before;
    }
    comments
}

/// Byte offset of `node` in the text of its tree.
fn start_offset(node: &CstNode) -> usize {
    let mut offset = 0;
    let mut current = node.clone();
    loop {
        offset += current
            .previous_siblings()
            .map(|sibling| sibling.to_string().len())
            .sum::<usize>();
        match current.parent() {
            Some(parent) => current = CstNode::Container(parent),
            None => return offset,
        }
    }
}

fn end_offset(node: &CstNode) -> usize {
    start_offset(node) + node.to_string().len()
}

fn to_native(node: &CstNode) -> NativeValue {
    match node {
        CstNode::Container(CstContainerNode::Object(object)) => {
            // Duplicate keys: the first one counts, as in `CstObject::get`,
            // which every edit goes through.
            let mut map = NativeMap::new();
            for prop in object.properties() {
                if let Some(name) = prop.decoded_name()
                    && !map.contains_key(&name)
                {
                    let value = prop
                        .value()
                        .map_or(NativeValue::Null, |node| to_native(&node));
                    map.insert(name, value);
                }
            }
            NativeValue::Object(map)
        }
        CstNode::Container(CstContainerNode::Array(array)) => {
            NativeValue::Array(array.elements().iter().map(to_native).collect())
        }
        CstNode::Leaf(CstLeafNode::StringLit(string)) => NativeValue::String(
            string
                .decoded_value()
                .unwrap_or_else(|_| string.raw_value()),
        ),
        CstNode::Leaf(CstLeafNode::NumberLit(number)) => number_value(&number.to_string()),
        CstNode::Leaf(CstLeafNode::BooleanLit(boolean)) => NativeValue::Bool(boolean.value()),
        CstNode::Leaf(CstLeafNode::WordLit(word)) => NativeValue::String(word.to_string()),
        _ => NativeValue::Null,
    }
}

fn number_value(raw: &str) -> NativeValue {
    let integral = !raw.contains(['.', 'e', 'E']);
    if integral && let Ok(value) = raw.parse::<i64>() {
        return NativeValue::Integer(value);
    }
    match raw.parse::<f64>() {
        Ok(value) => NativeValue::Float(value),
        Err(_) => NativeValue::String(raw.to_owned()),
    }
}

/// JSON has no NaN or infinity.
fn check_finite(value: &NativeValue) -> Result<(), CoreError> {
    match value {
        NativeValue::Float(value) if !value.is_finite() => Err(CoreError::new(
            ErrorCode::InvalidValue,
            format!("JSON has no {value}"),
        )),
        NativeValue::Array(items) => items.iter().try_for_each(check_finite),
        NativeValue::Object(map) => map.iter().try_for_each(|(_, value)| check_finite(value)),
        _ => Ok(()),
    }
}

/// `value` for the CST; floats are finite (see [`check_finite`]).
fn to_input(value: &NativeValue) -> CstInputValue {
    match value {
        NativeValue::Null => CstInputValue::Null,
        NativeValue::Bool(value) => CstInputValue::Bool(*value),
        NativeValue::Integer(value) => CstInputValue::Number(value.to_string()),
        // Debug keeps a fraction (`1.0`), so the number reads back as a float.
        NativeValue::Float(value) => CstInputValue::Number(format!("{value:?}")),
        NativeValue::String(value) | NativeValue::Datetime(value) => {
            CstInputValue::String(value.clone())
        }
        NativeValue::Array(items) => CstInputValue::Array(items.iter().map(to_input).collect()),
        NativeValue::Object(map) => CstInputValue::Object(
            map.iter()
                .map(|(key, value)| (key.to_owned(), to_input(value)))
                .collect(),
        ),
    }
}

/// A JSON string literal, escaped like the CST escapes the strings it writes.
fn json_string(value: &str) -> String {
    let mut text = String::with_capacity(value.len() + 2);
    text.push('"');
    for ch in value.chars() {
        match ch {
            '"' => text.push_str("\\\""),
            '\\' => text.push_str("\\\\"),
            '\u{08}' => text.push_str("\\b"),
            '\u{0c}' => text.push_str("\\f"),
            '\n' => text.push_str("\\n"),
            '\r' => text.push_str("\\r"),
            '\t' => text.push_str("\\t"),
            ch if ch.is_control() => text.push_str(&format!("\\u{:04x}", u32::from(ch))),
            ch => text.push(ch),
        }
    }
    text.push('"');
    text
}

fn owned(path: &[&str]) -> Vec<String> {
    path.iter().map(|key| (*key).to_owned()).collect()
}