Skip to main content

lsdocs_protocol/
lib.rs

1//! Message and capability types for the lsdocs plugin protocol.
2//!
3//! The host and plugins exchange requests and notifications. Each one is a
4//! marker type implementing [`Request`] or [`Notification`], which ties the
5//! method name to its parameter and result types; see [`request`] and
6//! [`notification`]. How messages are framed and sent is up to the `rpc`
7//! crate; this crate only defines what is inside them.
8//!
9//! ## Lifecycle
10//!
11//! 1. Host -> plugin: [`request::Initialize`]; the plugin answers with its
12//!    [`Capabilities`].
13//! 2. Host -> plugin: [`notification::Initialized`].
14//! 3. Phase requests, as the plugin's capabilities allow:
15//!    [`request::Parse`], [`request::ParseTransformEach`], then once
16//!    [`request::ParseTransformAll`], [`request::RenderTransformEach`],
17//!    [`request::Render`], then once [`request::RenderTransformAll`].
18//! 4. Host -> plugin: [`request::Shutdown`], then [`notification::Exit`].
19//!
20//! Plugins may send [`notification::Log`], [`notification::Progress`] and
21//! [`notification::Diagnostics`] at any time after initialization.
22//!
23//! ## Encoding
24//!
25//! Messages are MessagePack. Use [`msgpack::encode`] and [`msgpack::decode`],
26//! which write structs as maps (never positional arrays) so that fields can be
27//! added without breaking plugins in other languages. Field names are
28//! `snake_case`; optional fields are omitted when empty; unknown fields are
29//! ignored.
30
31use serde::{Deserialize, Serialize, de::DeserializeOwned};
32
33pub use lsdocs_doctree as doctree;
34use lsdocs_doctree::{Document, Metadata, Span, Value};
35
36/// Protocol version spoken by this crate: `MAJOR.MINOR`, with `-rc.N` for
37/// a release candidate. See [`compatible`] and "Versions" in
38/// `spec/wire.md`.
39pub const PROTOCOL_VERSION: &str = "1.0-rc.0";
40
41/// Whether peers speaking protocol versions `a` and `b` can talk: the same
42/// major version, and, if either is a release candidate, the very same
43/// version. Minor versions only add things older peers can ignore.
44pub fn compatible(a: &str, b: &str) -> bool {
45    let major = |v: &str| v.split(['.', '-']).next().map(str::to_owned);
46    let prerelease = |v: &str| v.contains('-');
47    if prerelease(a) || prerelease(b) {
48        return a == b;
49    }
50    major(a).is_some_and(|m| !m.is_empty() && major(b) == Some(m))
51}
52
53/// A request: a message that expects a response.
54pub trait Request {
55    /// Method name on the wire.
56    const METHOD: &'static str;
57    /// Parameters sent with the request.
58    type Params: Serialize + DeserializeOwned;
59    /// Value returned on success.
60    type Result: Serialize + DeserializeOwned;
61}
62
63/// A notification: a message with no response.
64pub trait Notification {
65    /// Method name on the wire.
66    const METHOD: &'static str;
67    /// Parameters sent with the notification.
68    type Params: Serialize + DeserializeOwned;
69}
70
71/// Requests, as marker types.
72pub mod request {
73    use super::*;
74
75    macro_rules! requests {
76        ($( $(#[$m:meta])* $name:ident = $method:literal, $params:ty => $result:ty; )*) => {$(
77            $(#[$m])*
78            #[derive(Debug)]
79            pub enum $name {}
80            impl Request for $name {
81                const METHOD: &'static str = $method;
82                type Params = $params;
83                type Result = $result;
84            }
85        )*};
86    }
87
88    requests! {
89        /// Host -> plugin. Starts the session and exchanges capabilities.
90        Initialize = "initialize", InitializeParams => InitializeResult;
91        /// Host -> plugin. Asks the plugin to finish outstanding work; it
92        /// should then expect [`notification::Exit`](super::notification::Exit).
93        Shutdown = "shutdown", () => ();
94        /// Host -> plugin. Parses one source file into a document.
95        Parse = "parse", ParseParams => ParseResult;
96        /// Host -> plugin. First transform pass: gathers data from one
97        /// document, e.g. its headings for a site-wide index.
98        ParseTransformEach = "parse/transform/each", ParseTransformEachParams => ParseTransformEachResult;
99        /// Host -> plugin. Sent once between the two transform passes, to a
100        /// plugin that collects: everything collected from all documents.
101        /// The `render/transform/each` requests that follow omit it. The plugin
102        /// may answer with documents it generates from that data (an index
103        /// page, say), which join the site.
104        ParseTransformAll = "parse/transform/all", ParseTransformAllParams => ParseTransformAllResult;
105        /// Host -> plugin. Second transform pass: rewrites one document, with
106        /// the data collected from all documents.
107        RenderTransformEach = "render/transform/each", RenderTransformEachParams => RenderTransformEachResult;
108        /// Host -> plugin. Renders one document to an output format.
109        Render = "render", RenderParams => RenderResult;
110        /// Plugin -> host. Parses a piece of text with the parser that
111        /// takes files of an extension, e.g. a doc comment written in
112        /// Markdown, while the plugin works on a request. The result is not
113        /// normalized.
114        HostParse = "host/parse", HostParseParams => ParseResult;
115        /// Host -> plugin. Sent once after every document is rendered, if
116        /// the renderer asked for it ([`RenderCapability::site`]): returns
117        /// site-wide files such as a sitemap.
118        RenderTransformAll = "render/transform/all", RenderTransformAllParams => RenderTransformAllResult;
119    }
120}
121
122/// Notifications, as marker types.
123pub mod notification {
124    use super::*;
125
126    macro_rules! notifications {
127        ($( $(#[$m:meta])* $name:ident = $method:literal, $params:ty; )*) => {$(
128            $(#[$m])*
129            #[derive(Debug)]
130            pub enum $name {}
131            impl Notification for $name {
132                const METHOD: &'static str = $method;
133                type Params = $params;
134            }
135        )*};
136    }
137
138    notifications! {
139        /// Host -> plugin. Sent after the initialize response; phase requests
140        /// may follow.
141        Initialized = "initialized", ();
142        /// Host -> plugin. The plugin should exit now.
143        Exit = "exit", ();
144        /// Either direction. Cancels an in-flight request.
145        Cancel = "$/cancel", CancelParams;
146        /// Plugin -> host. A log line.
147        Log = "log", LogParams;
148        /// Plugin -> host. Progress on long-running work.
149        Progress = "progress", ProgressParams;
150        /// Plugin -> host. Diagnostics not tied to a particular response.
151        Diagnostics = "diagnostics", DiagnosticsParams;
152    }
153}
154
155// ---------------------------------------------------------------------------
156// Initialize
157// ---------------------------------------------------------------------------
158
159/// Name and version of a program taking part in the protocol.
160#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
161#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
162pub struct ProgramInfo {
163    /// Program name.
164    pub name: String,
165    /// Program version.
166    pub version: String,
167}
168
169/// Site-wide settings plugins may need, e.g. for building links.
170#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
171#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
172pub struct SiteInfo {
173    /// Site title.
174    #[serde(default, skip_serializing_if = "Option::is_none")]
175    pub title: Option<String>,
176    /// URL or path prefix the site is served from.
177    #[serde(default, skip_serializing_if = "Option::is_none")]
178    pub base_url: Option<String>,
179    /// Absolute path of the site's directory (where `lsdocs.toml` is).
180    /// Resolve relative paths from plugin settings against this, not the
181    /// process's working directory: builtin plugins run inside the host.
182    #[serde(default, skip_serializing_if = "Option::is_none")]
183    pub root: Option<String>,
184    /// Absolute path of the source directory, which document `source`
185    /// paths are relative to (e.g. for parsers that read included files).
186    #[serde(default, skip_serializing_if = "Option::is_none")]
187    pub source_dir: Option<String>,
188    /// Every file under the source directory (documents and static assets
189    /// alike), relative to it with `/` separators, sorted. Lets transformers
190    /// check links to files that are not documents, such as images.
191    #[serde(default, skip_serializing_if = "Vec::is_empty")]
192    pub files: Vec<String>,
193}
194
195/// Parameters of [`request::Initialize`].
196#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
197#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
198pub struct InitializeParams {
199    /// Protocol version the host speaks, e.g. `"1.0"`.
200    pub protocol_version: String,
201    /// The host.
202    pub host: ProgramInfo,
203    /// The site being built.
204    #[serde(default)]
205    pub site: SiteInfo,
206    /// Where the plugin's settings are.
207    #[serde(default)]
208    pub config: ConfigInfo,
209}
210
211/// Where a plugin's settings are: the site's `.config/` directory, whose
212/// layout is the plugin's business (the recommended one is
213/// `<vendor>/<name>/`), and the plugin's name in the site config.
214#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
215#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
216pub struct ConfigInfo {
217    /// Absolute path of `.config/` (next to `lsdocs.toml`), whether or
218    /// not it exists.
219    #[serde(default)]
220    pub dir: String,
221    /// The plugin's name in the site config (`name = "..."`), so that two
222    /// instances of a plugin can keep separate settings.
223    #[serde(default)]
224    pub name: String,
225}
226
227/// Result of [`request::Initialize`].
228#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
229#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
230pub struct InitializeResult {
231    /// Protocol version the plugin speaks. The host ends the session if it
232    /// is not [`compatible`] with its own.
233    pub protocol_version: String,
234    /// The plugin.
235    pub plugin: ProgramInfo,
236    /// What the plugin can do.
237    pub capabilities: Capabilities,
238    /// The files the plugin read its settings from, relative to
239    /// `.config/` (or absolute), including ones it looked for and did not
240    /// find. The host digests them into the plugin's cache keys, so a
241    /// change to one (or creating one) is a change of settings.
242    #[serde(default, skip_serializing_if = "Vec::is_empty")]
243    pub config_files: Vec<String>,
244}
245
246/// What a plugin can do. A phase the plugin does not support is omitted.
247#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
248#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
249pub struct Capabilities {
250    /// Present if the plugin handles [`request::Parse`].
251    #[serde(default, skip_serializing_if = "Option::is_none")]
252    pub parse: Option<ParseCapability>,
253    /// Present if the plugin handles the transform requests.
254    #[serde(default, skip_serializing_if = "Option::is_none")]
255    pub transform: Option<TransformCapability>,
256    /// Present if the plugin handles [`request::Render`].
257    #[serde(default, skip_serializing_if = "Option::is_none")]
258    pub render: Option<RenderCapability>,
259    /// Most requests the plugin can work on at once; omitted means no
260    /// limit. Python plugins report 1 because of the GIL.
261    #[serde(default, skip_serializing_if = "Option::is_none")]
262    pub max_concurrency: Option<u32>,
263    /// Present if the plugin's results may be cached: they depend only on
264    /// the request, the site settings, the plugin's name, version and
265    /// options, and this key. A plugin that reads anything else (say, a
266    /// template file its options name) puts a digest of it in the key, so
267    /// the cache is invalidated when that changes. Omitted means never
268    /// cache.
269    #[serde(default, skip_serializing_if = "Option::is_none")]
270    pub cache: Option<String>,
271    /// Directives and roles the plugin handles. The host passes every
272    /// plugin's syntax to parsers ([`ParseParams::syntax`]), which turn it
273    /// into `custom` nodes for the plugin to transform.
274    #[serde(default, skip_serializing_if = "Syntax::is_empty")]
275    pub syntax: Syntax,
276}
277
278/// Syntax extensions: directives and roles that plugins give meaning to.
279///
280/// Parsers read them with their format's syntax (in reStructuredText,
281/// `.. name:: argument` and `` :name:`text` ``; in Markdown, MyST's
282/// ```` ```{name} argument ```` fences and `` {name}`text` ``) and make
283/// format-neutral nodes of them; see "Syntax extensions" in
284/// `spec/wire.md` for the shape.
285#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
286#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
287pub struct Syntax {
288    /// Block-level directives.
289    #[serde(default, skip_serializing_if = "Vec::is_empty")]
290    pub directives: Vec<DirectiveSyntax>,
291    /// Inline roles.
292    #[serde(default, skip_serializing_if = "Vec::is_empty")]
293    pub roles: Vec<RoleSyntax>,
294}
295
296impl Syntax {
297    /// Whether there are neither directives nor roles.
298    pub fn is_empty(&self) -> bool {
299        self.directives.is_empty() && self.roles.is_empty()
300    }
301
302    /// Adds `other`'s directives and roles, keeping the first declaration
303    /// of a name.
304    pub fn merge(&mut self, other: &Syntax) {
305        for d in &other.directives {
306            if !self.directives.iter().any(|x| x.name == d.name) {
307                self.directives.push(d.clone());
308            }
309        }
310        for r in &other.roles {
311            if !self.roles.iter().any(|x| x.name == r.name) {
312                self.roles.push(r.clone());
313            }
314        }
315    }
316
317    /// The directive called `name`, if declared.
318    pub fn directive(&self, name: &str) -> Option<&DirectiveSyntax> {
319        self.directives.iter().find(|d| d.name == name)
320    }
321
322    /// Whether a role called `name` is declared.
323    pub fn has_role(&self, name: &str) -> bool {
324        self.roles.iter().any(|r| r.name == name)
325    }
326}
327
328/// A directive: what it accepts, so parsers can split its parts.
329#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
330#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
331pub struct DirectiveSyntax {
332    /// The directive's name, in lower case, e.g. `"versionadded"`.
333    pub name: String,
334    /// How many arguments it requires.
335    #[serde(default, skip_serializing_if = "is_zero")]
336    pub required_arguments: u32,
337    /// How many more arguments it accepts.
338    #[serde(default, skip_serializing_if = "is_zero")]
339    pub optional_arguments: u32,
340    /// Whether the last argument may contain whitespace (it takes the rest
341    /// of the argument text).
342    #[serde(default, skip_serializing_if = "is_false")]
343    pub final_argument_whitespace: bool,
344    /// How the argument is read.
345    #[serde(default, skip_serializing_if = "ArgumentSyntax::is_text")]
346    pub argument: ArgumentSyntax,
347    /// The options it accepts, by name.
348    #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
349    pub options: std::collections::BTreeMap<String, OptionSyntax>,
350    /// What its content is.
351    #[serde(default, skip_serializing_if = "ContentSyntax::is_none")]
352    pub content: ContentSyntax,
353}
354
355/// How a directive's argument is read.
356#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
357#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
358#[serde(rename_all = "snake_case")]
359pub enum ArgumentSyntax {
360    /// Plain text, kept as written.
361    #[default]
362    Text,
363    /// Inline markup, parsed as well as kept as text.
364    Inline,
365}
366
367impl ArgumentSyntax {
368    fn is_text(&self) -> bool {
369        *self == Self::Text
370    }
371}
372
373/// What a directive option takes.
374#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
375#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
376#[serde(rename_all = "snake_case")]
377pub enum OptionSyntax {
378    /// No value.
379    Flag,
380    /// A value, which may be empty.
381    #[default]
382    Value,
383    /// A value that must not be empty.
384    Required,
385}
386
387/// What a directive's content is.
388#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
389#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
390#[serde(rename_all = "snake_case")]
391pub enum ContentSyntax {
392    /// The directive takes no content.
393    #[default]
394    None,
395    /// Block markup, parsed into the node's children.
396    Blocks,
397    /// Text kept as written (code, a list of document names, ...).
398    Text,
399}
400
401impl ContentSyntax {
402    fn is_none(&self) -> bool {
403        *self == Self::None
404    }
405}
406
407/// A role: inline text with a name, e.g. `` :kbd:`Ctrl+C` ``.
408#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
409#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
410pub struct RoleSyntax {
411    /// The role's name, in lower case, e.g. `"kbd"`.
412    pub name: String,
413}
414
415fn is_zero(value: &u32) -> bool {
416    *value == 0
417}
418
419/// Parsing capability.
420#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
421#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
422pub struct ParseCapability {
423    /// File extensions handled, without the dot, e.g. `["md", "markdown"]`.
424    pub extensions: Vec<String>,
425}
426
427/// Transform capability.
428#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
429#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
430pub struct TransformCapability {
431    /// Node kinds the transformer looks at (see `Node::kind` in the doctree
432    /// crate, e.g. `"heading"` or `"custom:mermaid"`). Empty means the whole
433    /// document.
434    #[serde(default, skip_serializing_if = "Vec::is_empty")]
435    pub nodes: Vec<String>,
436    /// Whether the plugin handles [`request::ParseTransformEach`]. If false,
437    /// only [`request::RenderTransformEach`] is sent.
438    #[serde(default)]
439    pub each: bool,
440}
441
442/// Rendering capability.
443#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
444#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
445pub struct RenderCapability {
446    /// Output formats produced, e.g. `["html"]`.
447    pub formats: Vec<String>,
448    /// Whether the plugin handles [`request::RenderTransformAll`].
449    #[serde(default, skip_serializing_if = "is_false")]
450    pub all: bool,
451}
452
453fn is_false(value: &bool) -> bool {
454    !value
455}
456
457// ---------------------------------------------------------------------------
458// Phases
459// ---------------------------------------------------------------------------
460
461/// Parameters of [`request::Parse`].
462#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
463#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
464pub struct ParseParams {
465    /// Path of the file relative to the source directory, with `/`
466    /// separators. Becomes the document's `source`.
467    pub source: String,
468    /// The file's text.
469    pub text: String,
470    /// The directives and roles plugins declared ([`Capabilities::syntax`]),
471    /// for parsers that support syntax extensions.
472    #[serde(default, skip_serializing_if = "Syntax::is_empty")]
473    pub syntax: Syntax,
474}
475
476/// Parameters of [`request::HostParse`].
477#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
478#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
479pub struct HostParseParams {
480    /// The extension of the files whose parser should parse the text,
481    /// without the dot, e.g. `"md"` or `"rst"`.
482    pub extension: String,
483    /// The source path to give the parsed document (and its diagnostics),
484    /// usually the document the text will be part of.
485    pub source: String,
486    /// The text.
487    pub text: String,
488}
489
490/// Result of [`request::Parse`].
491#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
492#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
493pub struct ParseResult {
494    /// The parsed document.
495    pub document: Document,
496    /// Problems found while parsing.
497    #[serde(default, skip_serializing_if = "Vec::is_empty")]
498    pub diagnostics: Vec<Diagnostic>,
499    /// Files the result depends on besides the request, such as included
500    /// files: absolute paths, or paths relative to the site directory
501    /// (`site.root`), with `/` separators. A cached result is only reused
502    /// while they are unchanged (a file that did not exist must still not
503    /// exist), and `lsdocs serve` rebuilds when they change. List files
504    /// looked for but missing too.
505    #[serde(default, skip_serializing_if = "Vec::is_empty")]
506    pub dependencies: Vec<String>,
507}
508
509/// Parameters of [`request::ParseTransformEach`].
510#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
511#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
512pub struct ParseTransformEachParams {
513    /// The document to collect from.
514    pub document: Document,
515}
516
517/// Result of [`request::ParseTransformEach`].
518#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
519#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
520pub struct ParseTransformEachResult {
521    /// Data gathered from the document, in any shape the plugin likes.
522    #[serde(default)]
523    pub data: Value,
524    /// Problems found.
525    #[serde(default, skip_serializing_if = "Vec::is_empty")]
526    pub diagnostics: Vec<Diagnostic>,
527    /// Files the result depends on besides the request, such as included
528    /// files: absolute paths, or paths relative to the site directory
529    /// (`site.root`), with `/` separators. A cached result is only reused
530    /// while they are unchanged (a file that did not exist must still not
531    /// exist), and `lsdocs serve` rebuilds when they change. List files
532    /// looked for but missing too.
533    #[serde(default, skip_serializing_if = "Vec::is_empty")]
534    pub dependencies: Vec<String>,
535}
536
537/// Parameters of [`request::ParseTransformAll`].
538#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
539#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
540pub struct ParseTransformAllParams {
541    /// What this plugin collected from every document: a map from each
542    /// document's `source` to its collected `data`.
543    #[serde(default)]
544    pub collected: Value,
545}
546
547/// Result of [`request::ParseTransformAll`].
548#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
549#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
550pub struct ParseTransformAllResult {
551    /// Documents the plugin generates, with no source file: each one's
552    /// `source` is a path no source file has (it names the output, as a
553    /// source path would). The host normalizes them, and they go through
554    /// this plugin's apply pass, the transformers after it and rendering
555    /// like any other document.
556    #[serde(default, skip_serializing_if = "Vec::is_empty")]
557    pub documents: Vec<Document>,
558    /// Problems found.
559    #[serde(default, skip_serializing_if = "Vec::is_empty")]
560    pub diagnostics: Vec<Diagnostic>,
561    /// Files the result depends on besides the request, such as included
562    /// files: absolute paths, or paths relative to the site directory
563    /// (`site.root`), with `/` separators. A cached result is only reused
564    /// while they are unchanged (a file that did not exist must still not
565    /// exist), and `lsdocs serve` rebuilds when they change. List files
566    /// looked for but missing too.
567    #[serde(default, skip_serializing_if = "Vec::is_empty")]
568    pub dependencies: Vec<String>,
569}
570
571/// Parameters of [`request::RenderTransformEach`].
572#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
573#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
574pub struct RenderTransformEachParams {
575    /// The document to transform.
576    pub document: Document,
577    /// What this plugin collected from every document: a map from each
578    /// document's `source` to its collected `data`. Null if the plugin does
579    /// not collect. Over the wire the host leaves it null and sends it once
580    /// beforehand with [`request::ParseTransformAll`]; the plugin SDK fills
581    /// it back in, so handlers always see it here.
582    #[serde(default)]
583    pub collected: Value,
584}
585
586/// Result of [`request::RenderTransformEach`].
587#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
588#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
589pub struct RenderTransformEachResult {
590    /// The transformed document.
591    pub document: Document,
592    /// Problems found.
593    #[serde(default, skip_serializing_if = "Vec::is_empty")]
594    pub diagnostics: Vec<Diagnostic>,
595    /// Files the result depends on besides the request, such as included
596    /// files: absolute paths, or paths relative to the site directory
597    /// (`site.root`), with `/` separators. A cached result is only reused
598    /// while they are unchanged (a file that did not exist must still not
599    /// exist), and `lsdocs serve` rebuilds when they change. List files
600    /// looked for but missing too.
601    #[serde(default, skip_serializing_if = "Vec::is_empty")]
602    pub dependencies: Vec<String>,
603}
604
605/// Parameters of [`request::Render`].
606#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
607#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
608pub struct RenderParams {
609    /// The document to render.
610    pub document: Document,
611    /// Output format, one of the plugin's [`RenderCapability::formats`].
612    pub format: String,
613}
614
615/// Result of [`request::Render`].
616#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
617#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
618pub struct RenderResult {
619    /// The rendered output. Sent as MessagePack `bin`.
620    #[serde(with = "serde_bytes")]
621    #[cfg_attr(feature = "schema", schemars(with = "Vec<u8>"))]
622    pub output: Vec<u8>,
623    /// File extension for the output, without the dot, e.g. `"html"`.
624    pub extension: String,
625    /// Problems found.
626    #[serde(default, skip_serializing_if = "Vec::is_empty")]
627    pub diagnostics: Vec<Diagnostic>,
628    /// Data about the page, in any shape the plugin likes, handed back to
629    /// it in [`RenderedPage::data`] at [`request::RenderTransformAll`]
630    /// (a search index's entry for the page, say). Cached with the
631    /// result, so a page that is not rendered again keeps it. Omitted
632    /// when null.
633    #[serde(default, skip_serializing_if = "Value::is_null")]
634    pub data: Value,
635}
636
637/// Parameters of [`request::RenderTransformAll`].
638#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
639#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
640pub struct RenderTransformAllParams {
641    /// Output format the pages were rendered to.
642    pub format: String,
643    /// Every page rendered, sorted by source path.
644    #[serde(default)]
645    pub pages: Vec<RenderedPage>,
646}
647
648/// A page written by the render phase.
649#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
650#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
651pub struct RenderedPage {
652    /// The document's source path.
653    pub source: String,
654    /// Where the page was written, relative to the output directory, with
655    /// `/` separators, e.g. `guide/intro.html`.
656    pub path: String,
657    /// The document's metadata after the transform phase.
658    #[serde(default, skip_serializing_if = "Metadata::is_empty")]
659    pub metadata: Metadata,
660    /// The `data` of the page's [`RenderResult`]. Omitted when null.
661    #[serde(default, skip_serializing_if = "Value::is_null")]
662    pub data: Value,
663}
664
665/// Result of [`request::RenderTransformAll`].
666#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
667#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
668pub struct RenderTransformAllResult {
669    /// Extra files to write.
670    #[serde(default, skip_serializing_if = "Vec::is_empty")]
671    pub files: Vec<OutputFile>,
672    /// Problems found.
673    #[serde(default, skip_serializing_if = "Vec::is_empty")]
674    pub diagnostics: Vec<Diagnostic>,
675}
676
677/// A file for the host to write.
678#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
679#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
680pub struct OutputFile {
681    /// Path relative to the output directory, with `/` separators. It may
682    /// not leave the output directory or replace a rendered page.
683    pub path: String,
684    /// The file's content. Sent as MessagePack `bin`.
685    #[serde(with = "serde_bytes")]
686    #[cfg_attr(feature = "schema", schemars(with = "Vec<u8>"))]
687    pub output: Vec<u8>,
688}
689
690// ---------------------------------------------------------------------------
691// Diagnostics and notifications
692// ---------------------------------------------------------------------------
693
694/// A problem to report to the user, modeled on LSP diagnostics.
695#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
696#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
697pub struct Diagnostic {
698    /// How serious the problem is.
699    pub severity: Severity,
700    /// What is wrong.
701    pub message: String,
702    /// Source file the problem is in, relative to the source directory.
703    #[serde(default, skip_serializing_if = "Option::is_none")]
704    pub source: Option<String>,
705    /// Where in `source` the problem is.
706    #[serde(default, skip_serializing_if = "Option::is_none")]
707    pub span: Option<Span>,
708    /// A short identifier for the kind of problem, e.g. `"broken-link"`.
709    #[serde(default, skip_serializing_if = "Option::is_none")]
710    pub code: Option<String>,
711}
712
713/// Severity of a [`Diagnostic`].
714#[derive(
715    Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize,
716)]
717#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
718#[serde(rename_all = "snake_case")]
719pub enum Severity {
720    /// The build fails.
721    #[default]
722    Error,
723    /// Probably a mistake, but the build continues.
724    Warning,
725    /// Worth knowing.
726    Info,
727    /// A suggestion.
728    Hint,
729}
730
731/// Parameters of [`notification::Cancel`].
732#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
733#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
734pub struct CancelParams {
735    /// Id of the request to cancel.
736    pub id: u32,
737}
738
739/// Parameters of [`notification::Log`].
740#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
741#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
742pub struct LogParams {
743    /// Log level.
744    pub level: LogLevel,
745    /// The message.
746    pub message: String,
747}
748
749/// Level of a [`LogParams`] message.
750#[derive(
751    Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize,
752)]
753#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
754#[serde(rename_all = "snake_case")]
755pub enum LogLevel {
756    /// Errors.
757    Error,
758    /// Warnings.
759    Warn,
760    /// General information.
761    #[default]
762    Info,
763    /// Debugging detail.
764    Debug,
765    /// Very verbose detail.
766    Trace,
767}
768
769/// Parameters of [`notification::Progress`].
770#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
771#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
772pub struct ProgressParams {
773    /// What is being worked on.
774    pub message: String,
775    /// Percent complete, 0-100, if known.
776    #[serde(default, skip_serializing_if = "Option::is_none")]
777    pub percentage: Option<u8>,
778}
779
780/// Parameters of [`notification::Diagnostics`].
781#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
782#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
783pub struct DiagnosticsParams {
784    /// The diagnostics.
785    pub diagnostics: Vec<Diagnostic>,
786}
787
788// ---------------------------------------------------------------------------
789// Encoding
790// ---------------------------------------------------------------------------
791
792/// MessagePack encoding following the protocol's rules.
793pub mod msgpack {
794    use serde::{Serialize, de::DeserializeOwned};
795
796    pub use rmp_serde::decode::Error as DecodeError;
797    pub use rmp_serde::encode::Error as EncodeError;
798
799    /// Encodes a value. Structs become maps keyed by field name, never
800    /// positional arrays.
801    pub fn encode<T: Serialize + ?Sized>(value: &T) -> Result<Vec<u8>, EncodeError> {
802        rmp_serde::to_vec_named(value)
803    }
804
805    /// Decodes a value.
806    pub fn decode<T: DeserializeOwned>(bytes: &[u8]) -> Result<T, DecodeError> {
807        rmp_serde::from_slice(bytes)
808    }
809}
810
811#[cfg(test)]
812mod tests {
813    #![allow(clippy::unwrap_used)]
814    #[test]
815    fn versions_are_compatible_within_a_major_version() {
816        use super::compatible;
817        assert!(compatible("1.0", "1.3"));
818        assert!(!compatible("1.0", "2.0"));
819        assert!(compatible("1.0-rc.0", "1.0-rc.0"));
820        assert!(!compatible("1.0-rc.0", "1.0-rc.1"));
821        assert!(!compatible("1.0-rc.0", "1.0"));
822        assert!(!compatible("", ""));
823    }
824
825    use super::*;
826    use lsdocs_doctree::{Heading, text};
827    use std::fmt::Debug;
828
829    fn round_trip<T>(value: &T) -> Vec<u8>
830    where
831        T: Serialize + DeserializeOwned + PartialEq + Debug,
832    {
833        let bytes = msgpack::encode(value).unwrap();
834        assert_eq!(&msgpack::decode::<T>(&bytes).unwrap(), value);
835        bytes
836    }
837
838    /// Whether `bytes` starts with a MessagePack map header.
839    fn is_map(bytes: &[u8]) -> bool {
840        matches!(bytes[0], 0x80..=0x8f | 0xde | 0xdf)
841    }
842
843    #[test]
844    fn structs_encode_as_maps() {
845        let bytes = round_trip(&ProgramInfo {
846            name: "lsdocs".into(),
847            version: "0.1.0".into(),
848        });
849        assert!(is_map(&bytes), "{bytes:x?}");
850    }
851
852    #[test]
853    fn unit_enums_encode_as_strings() {
854        let bytes = round_trip(&Severity::Warning);
855        assert_eq!(bytes, b"\xa7warning");
856    }
857
858    #[test]
859    fn render_output_is_binary() {
860        let bytes = round_trip(&RenderResult {
861            output: b"<p>hi</p>".to_vec(),
862            extension: "html".into(),
863            ..RenderResult::default()
864        });
865        // `bin 8` header followed by the length, then the raw bytes.
866        let needle = b"\xc4\x09<p>hi</p>";
867        assert!(
868            bytes.windows(needle.len()).any(|w| w == needle),
869            "{bytes:x?}"
870        );
871    }
872
873    #[test]
874    fn documents_round_trip_through_msgpack() {
875        let mut document = Document::new("index.md");
876        document.children.push(
877            Heading {
878                level: 2,
879                children: vec![text("Hello")],
880                ..Heading::default()
881            }
882            .into(),
883        );
884        round_trip(&RenderTransformEachParams {
885            document,
886            collected: serde_json::json!({"index.md": ["Hello"]}),
887        });
888    }
889
890    #[test]
891    fn method_names() {
892        assert_eq!(request::ParseTransformEach::METHOD, "parse/transform/each");
893        assert_eq!(request::ParseTransformAll::METHOD, "parse/transform/all");
894        assert_eq!(
895            request::RenderTransformEach::METHOD,
896            "render/transform/each"
897        );
898        assert_eq!(request::RenderTransformAll::METHOD, "render/transform/all");
899        assert_eq!(request::HostParse::METHOD, "host/parse");
900        assert_eq!(notification::Cancel::METHOD, "$/cancel");
901        let each = serde_json::to_value(TransformCapability {
902            each: true,
903            ..TransformCapability::default()
904        })
905        .unwrap();
906        assert_eq!(each["each"], true);
907        let all = serde_json::to_value(RenderCapability {
908            all: true,
909            ..RenderCapability::default()
910        })
911        .unwrap();
912        assert_eq!(all["all"], true);
913    }
914}