Skip to main content

nb_api/
types.rs

1//! Public wire types for body-aware reads, edits, and commit outcomes.
2//!
3//! 0.4.0 is text-first: every structured textual field is a JSON `String`.
4//! The crate is base64-free; callers needing JSON transport base64 do it at
5//! the wire layer. Non-UTF-8-but-text files surface as typed
6//! [`crate::error::NbError::NonUtf8`]; the single raw-bytes escape hatch is
7//! `NbClient::read_note_source_bytes`.
8
9use serde::{Deserialize, Serialize};
10
11use crate::error::NbError;
12use crate::fingerprint::Fingerprint;
13use crate::parser::{DocumentKind, TodoState};
14
15/// Address an existing note by selector or notebook-relative path.
16#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
17#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
18#[serde(tag = "type", rename_all = "lowercase")]
19pub enum NoteTarget {
20    Selector { value: String },
21    Path { value: String },
22}
23
24impl NoteTarget {
25    pub fn selector(value: impl Into<String>) -> Self {
26        Self::Selector {
27            value: value.into(),
28        }
29    }
30
31    pub fn path(value: impl Into<String>) -> Self {
32        Self::Path {
33            value: value.into(),
34        }
35    }
36
37    pub fn value(&self) -> &str {
38        match self {
39            Self::Selector { value } | Self::Path { value } => value,
40        }
41    }
42}
43
44/// One body fragment exposed by structured show.
45///
46/// `bytes` is the fragment text (UTF-8); `start_byte`/`end_byte` are offsets
47/// into `ShowNote.source`, so `body == concat(fragment.bytes)` and each
48/// `source[start_byte..end_byte] == fragment.bytes`.
49#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
50#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
51pub struct BodyFragment {
52    pub index: u32,
53    pub bytes: String,
54    pub start_byte: u32,
55    pub end_byte: u32,
56}
57
58/// Structured `show_note` result.
59#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
60#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
61pub struct ShowNote {
62    pub selector: String,
63    pub path: String,
64    pub kind: DocumentKind,
65    pub todo_state: Option<TodoState>,
66    /// Full raw title line including trailing newline, as UTF-8.
67    pub title: Option<String>,
68    pub title_text: Option<String>,
69    pub tags: Vec<String>,
70    pub body_fragments: Vec<BodyFragment>,
71    /// Derivable (`body_fragments.len() <= 1`); kept for wire convenience.
72    pub body_contiguous: bool,
73    /// Concatenated body-fragment bytes (excludes title H1 + tags).
74    pub body: String,
75    pub fingerprint: Fingerprint,
76    /// Full file bytes verbatim, as UTF-8.
77    pub source: String,
78    /// Numeric `.index` id when resolvable via `.index` scan.
79    #[serde(default, skip_serializing_if = "Option::is_none")]
80    pub numeric_id: Option<u32>,
81}
82
83/// Versioned body-line authenticity token: `b3l1:<32 lowercase hex>`.
84#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
85#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
86#[serde(transparent)]
87pub struct LineAnchor(String);
88
89impl LineAnchor {
90    pub const PREFIX: &'static str = "b3l1:";
91
92    pub fn as_str(&self) -> &str {
93        &self.0
94    }
95
96    pub fn from_line_bytes(line_with_terminator_or_eof_marker: &[u8]) -> Self {
97        let hash = blake3::hash(line_with_terminator_or_eof_marker);
98        let hex = hash.to_hex();
99        Self(format!("{}{}", Self::PREFIX, &hex[..32]))
100    }
101
102    pub fn parse(s: &str) -> Result<Self, NbError> {
103        if !s.starts_with(Self::PREFIX) {
104            return Err(NbError::ValidationError {
105                reason: format!("unknown line anchor prefix in {s:?}"),
106                location: None,
107            });
108        }
109        let hex = &s[Self::PREFIX.len()..];
110        if hex.len() != 32
111            || !hex
112                .chars()
113                .all(|c| c.is_ascii_hexdigit() && !c.is_ascii_uppercase())
114        {
115            return Err(NbError::ValidationError {
116                reason: format!("invalid line anchor hex in {s:?}"),
117                location: None,
118            });
119        }
120        Ok(Self(s.to_string()))
121    }
122}
123
124impl std::fmt::Display for LineAnchor {
125    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
126        f.write_str(&self.0)
127    }
128}
129
130/// Document-level end-of-line marker.
131///
132/// `Lf` for `\n`, `CrLf` for `\r\n`. Bare `\r` is not a supported EOL and is
133/// preserved verbatim in line text; documents without a supported EOL report
134/// `eol: None` on [`ShowNoteLines`].
135#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
136#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
137#[serde(rename_all = "lowercase")]
138pub enum LineEol {
139    Lf,
140    CrLf,
141}
142
143impl LineEol {
144    pub fn as_bytes(self) -> &'static [u8] {
145        match self {
146            Self::Lf => b"\n",
147            Self::CrLf => b"\r\n",
148        }
149    }
150}
151
152/// One enumerated body line (line text without terminator).
153///
154/// Unknown JSON fields (including the removed 0.3.x `terminator`) are ignored
155/// on deserialization for forward compatibility.
156#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
157#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
158pub struct NoteLine {
159    pub number: u32,
160    pub anchor: LineAnchor,
161    pub text: String,
162}
163
164/// Windowed body-line listing with a document-level EOL declaration.
165#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
166#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
167pub struct ShowNoteLines {
168    pub selector: String,
169    pub path: String,
170    pub kind: DocumentKind,
171    pub total_lines: u32,
172    pub offset: u32,
173    pub limit: u32,
174    pub next_offset: Option<u32>,
175    pub lines: Vec<NoteLine>,
176    pub title: Option<String>,
177    pub tags: Vec<String>,
178    pub body_fingerprint: Fingerprint,
179    /// First-supported-EOL declaration; `None` for empty / single-line-no-EOL
180    /// / CR-only bodies.
181    pub eol: Option<LineEol>,
182    /// Whether the body ends with `eol` bytes.
183    pub has_final_eol: bool,
184    /// Numeric `.index` id when resolvable via `.index` scan.
185    #[serde(default, skip_serializing_if = "Option::is_none")]
186    pub numeric_id: Option<u32>,
187}
188
189/// Number + anchor reference to a body line.
190#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
191#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
192pub struct LineRef {
193    pub number: u32,
194    pub anchor: LineAnchor,
195}
196
197/// Insert position relative to a line or body boundary.
198#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
199#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
200#[serde(tag = "type", rename_all = "lowercase")]
201pub enum LinePosition {
202    Before { line: LineRef },
203    After { line: LineRef },
204    Boundary { at: BoundaryAt },
205}
206
207/// Virtual body boundaries (`^` / `$`).
208#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
209#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
210#[serde(rename_all = "lowercase")]
211pub enum BoundaryAt {
212    Caret,
213    Dollar,
214}
215
216/// One line-oriented edit in an `edit_note_lines` batch.
217///
218/// `content` is bare text (no terminator included; embedded `\r` preserved).
219/// The library appends document `eol` bytes when materializing edits.
220#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
221#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
222#[serde(tag = "type", rename_all = "lowercase")]
223pub enum LineEdit {
224    Insert {
225        at: LinePosition,
226        content: String,
227    },
228    Delete {
229        start: LineRef,
230        end: LineRef,
231    },
232    Replace {
233        start: LineRef,
234        end: LineRef,
235        content: String,
236    },
237}
238
239/// Substring occurrence selector.
240#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
241#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
242#[serde(tag = "type", rename_all = "lowercase")]
243pub enum Occurrence {
244    First,
245    All,
246    Nth { n: u32 },
247}
248
249/// One search hit within a body line.
250#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
251#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
252pub struct NoteLineHit {
253    pub number: u32,
254    pub anchor: LineAnchor,
255    pub start_byte: u32,
256    pub end_byte: u32,
257    #[serde(skip_serializing_if = "Option::is_none")]
258    pub text: Option<String>,
259}
260
261/// Result of `search_note_lines`.
262#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
263#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
264pub struct SearchNoteLines {
265    pub selector: String,
266    pub path: String,
267    pub kind: DocumentKind,
268    pub hits: Vec<NoteLineHit>,
269    pub body_fingerprint: Fingerprint,
270}
271
272/// Outcome of one plan op after a successful commit.
273#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
274#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
275pub struct OpOutcome {
276    pub index: u32,
277    pub path: Option<String>,
278    pub selector: Option<String>,
279    /// Numeric `.index` id when known (pinned `Option<u32>` type).
280    #[serde(default, skip_serializing_if = "Option::is_none")]
281    pub numeric_id: Option<u32>,
282    pub noop: bool,
283    #[serde(skip_serializing_if = "Option::is_none")]
284    pub fingerprint: Option<Fingerprint>,
285}
286
287/// Structured result of [`crate::Transaction::commit`].
288#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
289#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
290pub struct CommitOutcome {
291    pub commit_created: bool,
292    pub revision_id: Option<String>,
293    pub pre_revision: String,
294    pub ops: Vec<OpOutcome>,
295}