merman 0.4.1

Rust, headless Mermaid implementation (1:1 parity; pinned to mermaid@11.12.3).
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
#![forbid(unsafe_code)]

//! `merman` is a headless, parity-focused Mermaid implementation in Rust.
//!
//! It is pinned to Mermaid `@11.12.3`; upstream Mermaid is treated as the spec. See:
//! - `docs/adr/0014-upstream-parity-policy.md`
//! - `docs/alignment/STATUS.md`
//!
//! # Features
//!
//! - `render`: enable layout + SVG rendering (`merman::render`)
//! - `raster`: enable PNG/JPG/PDF output via pure-Rust SVG rasterization/conversion

pub use merman_core::*;

#[cfg(feature = "render")]
pub mod render {
    pub use merman_render::math::{MathRenderer, NoopMathRenderer};
    pub use merman_render::model::LayoutedDiagram;
    pub use merman_render::svg::{SvgRenderOptions, foreign_object_label_fallback_svg_text};
    pub use merman_render::text::{
        DeterministicTextMeasurer, TextMeasurer, VendoredFontMetricsTextMeasurer,
    };
    pub use merman_render::{LayoutOptions, layout_parsed};

    #[cfg(feature = "raster")]
    pub mod raster;

    #[derive(Debug, thiserror::Error)]
    pub enum HeadlessError {
        #[error(transparent)]
        Parse(#[from] merman_core::Error),
        #[error(transparent)]
        Render(#[from] merman_render::Error),
    }

    pub type Result<T> = std::result::Result<T, HeadlessError>;

    /// Converts an arbitrary string into a conservative SVG `id` token suitable for embedding
    /// multiple Mermaid diagrams in the same UI tree.
    ///
    /// Mermaid uses the root `<svg id="...">` value as a prefix for internal ids like
    /// `chart-title-<id>` and marker ids under `<defs>`. If you inline multiple SVGs with the same
    /// id, those internal ids may collide.
    ///
    /// This helper:
    /// - trims whitespace
    /// - replaces unsupported characters with `-`
    /// - ensures the id starts with an ASCII letter by prefixing `m-` when needed
    pub fn sanitize_svg_id(raw: &str) -> String {
        let raw = raw.trim();
        if raw.is_empty() {
            return "m-untitled".to_string();
        }

        let mut iter = raw.chars();
        let Some(first_raw) = iter.next() else {
            return "m-untitled".to_string();
        };

        fn sanitize_char(ch: char) -> char {
            let ok = ch.is_ascii_alphanumeric() || ch == '-' || ch == '_' || ch == ':' || ch == '.';
            if ok { ch } else { '-' }
        }

        let first = sanitize_char(first_raw);
        let mut out = String::with_capacity(raw.len() + 2);
        let mut prev_dash = false;

        if !first.is_ascii_alphabetic() {
            out.push('m');
            if first != '-' {
                out.push('-');
                prev_dash = true;
            }
        }

        let push_sanitized = |ch: char, out: &mut String, prev_dash: &mut bool| {
            if ch == '-' {
                if *prev_dash {
                    return;
                }
                *prev_dash = true;
            } else {
                *prev_dash = false;
            }
            out.push(ch);
        };

        push_sanitized(first, &mut out, &mut prev_dash);
        for ch in iter {
            push_sanitized(sanitize_char(ch), &mut out, &mut prev_dash);
        }

        while out.ends_with('-') {
            out.pop();
        }

        if out.is_empty() || out == "m" {
            return "m-untitled".to_string();
        }
        out
    }

    #[cfg(test)]
    mod sanitize_svg_id_tests {
        use super::sanitize_svg_id;

        #[test]
        fn sanitize_svg_id_empty_is_untitled() {
            assert_eq!(sanitize_svg_id(""), "m-untitled");
            assert_eq!(sanitize_svg_id("   "), "m-untitled");
        }

        #[test]
        fn sanitize_svg_id_trims_and_replaces() {
            assert_eq!(sanitize_svg_id(" my diagram "), "my-diagram");
            assert_eq!(sanitize_svg_id("a b\tc"), "a-b-c");
        }

        #[test]
        fn sanitize_svg_id_prefixes_when_needed() {
            assert_eq!(sanitize_svg_id("1a"), "m-1a");
            assert_eq!(sanitize_svg_id("_a"), "m-_a");
            assert_eq!(sanitize_svg_id("-a"), "m-a");
        }

        #[test]
        fn sanitize_svg_id_collapses_and_trims_dashes() {
            assert_eq!(sanitize_svg_id("a----b"), "a-b");
            assert_eq!(sanitize_svg_id("abc--"), "abc");
            assert_eq!(sanitize_svg_id("--"), "m-untitled");
            assert_eq!(sanitize_svg_id("-"), "m-untitled");
        }

        #[test]
        fn sanitize_svg_id_keeps_allowed_punctuation() {
            assert_eq!(sanitize_svg_id("a:b.c_d"), "a:b.c_d");
        }

        #[test]
        fn sanitize_svg_id_m_is_reserved_for_untitled() {
            assert_eq!(sanitize_svg_id("m"), "m-untitled");
            assert_eq!(sanitize_svg_id("m-"), "m-untitled");
            assert_eq!(sanitize_svg_id("m--"), "m-untitled");
        }
    }

    /// Synchronous layout helper (executor-free).
    pub fn layout_diagram_sync(
        engine: &merman_core::Engine,
        text: &str,
        parse_options: merman_core::ParseOptions,
        layout_options: &LayoutOptions,
    ) -> Result<Option<LayoutedDiagram>> {
        let Some(parsed) = engine.parse_diagram_sync(text, parse_options)? else {
            return Ok(None);
        };
        Ok(Some(merman_render::layout_parsed(&parsed, layout_options)?))
    }

    /// Returns layout defaults intended for UI integrations that render headless SVG.
    ///
    /// This is a convenience wrapper around [`LayoutOptions::headless_svg_defaults`].
    pub fn headless_layout_options() -> LayoutOptions {
        LayoutOptions::headless_svg_defaults()
    }

    pub async fn layout_diagram(
        engine: &merman_core::Engine,
        text: &str,
        parse_options: merman_core::ParseOptions,
        layout_options: &LayoutOptions,
    ) -> Result<Option<LayoutedDiagram>> {
        // This async API is runtime-agnostic: layout is CPU-bound and does not perform I/O.
        // It executes synchronously and does not yield.
        layout_diagram_sync(engine, text, parse_options, layout_options)
    }

    pub fn render_layouted_svg(
        diagram: &LayoutedDiagram,
        measurer: &dyn TextMeasurer,
        svg_options: &SvgRenderOptions,
    ) -> Result<String> {
        Ok(merman_render::svg::render_layouted_svg(
            diagram,
            measurer,
            svg_options,
        )?)
    }

    /// Synchronous SVG render helper (executor-free).
    pub fn render_svg_sync(
        engine: &merman_core::Engine,
        text: &str,
        parse_options: merman_core::ParseOptions,
        layout_options: &LayoutOptions,
        svg_options: &SvgRenderOptions,
    ) -> Result<Option<String>> {
        let Some(parsed) = engine.parse_diagram_for_render_model_sync(text, parse_options)? else {
            return Ok(None);
        };

        let layout = merman_render::layout_parsed_render_layout_only(&parsed, layout_options)?;
        let svg = merman_render::svg::render_layout_svg_parts_for_render_model_with_config(
            &layout,
            &parsed.model,
            &parsed.meta.effective_config,
            parsed.meta.title.as_deref(),
            layout_options.text_measurer.as_ref(),
            svg_options,
        )?;

        Ok(Some(svg))
    }

    /// Synchronous SVG render helper that applies a best-effort readability fallback for
    /// `<foreignObject>` labels.
    ///
    /// This is intended for raster outputs and UI previews where `<foreignObject>` is not
    /// supported. It does not aim for upstream Mermaid DOM parity.
    pub fn render_svg_readable_sync(
        engine: &merman_core::Engine,
        text: &str,
        parse_options: merman_core::ParseOptions,
        layout_options: &LayoutOptions,
        svg_options: &SvgRenderOptions,
    ) -> Result<Option<String>> {
        let Some(svg) = render_svg_sync(engine, text, parse_options, layout_options, svg_options)?
        else {
            return Ok(None);
        };
        Ok(Some(foreign_object_label_fallback_svg_text(&svg)))
    }

    pub async fn render_svg(
        engine: &merman_core::Engine,
        text: &str,
        parse_options: merman_core::ParseOptions,
        layout_options: &LayoutOptions,
        svg_options: &SvgRenderOptions,
    ) -> Result<Option<String>> {
        // This async API is runtime-agnostic: rendering is CPU-bound and does not perform I/O.
        // It executes synchronously and does not yield.
        render_svg_sync(engine, text, parse_options, layout_options, svg_options)
    }

    pub async fn render_svg_readable(
        engine: &merman_core::Engine,
        text: &str,
        parse_options: merman_core::ParseOptions,
        layout_options: &LayoutOptions,
        svg_options: &SvgRenderOptions,
    ) -> Result<Option<String>> {
        // This async API is runtime-agnostic: rendering is CPU-bound and does not perform I/O.
        // It executes synchronously and does not yield.
        render_svg_readable_sync(engine, text, parse_options, layout_options, svg_options)
    }

    /// Convenience wrapper that bundles an [`Engine`] and common options for headless rendering.
    ///
    /// This is intended for UI integrations where passing 4-5 separate parameters per call is
    /// noisy. It stays runtime-agnostic: all work is CPU-bound and does not perform I/O.
    #[derive(Clone)]
    pub struct HeadlessRenderer {
        pub engine: merman_core::Engine,
        pub parse: merman_core::ParseOptions,
        pub layout: LayoutOptions,
        pub svg: SvgRenderOptions,
    }

    impl Default for HeadlessRenderer {
        fn default() -> Self {
            Self {
                engine: merman_core::Engine::new(),
                parse: merman_core::ParseOptions::default(),
                layout: LayoutOptions::headless_svg_defaults(),
                svg: SvgRenderOptions::default(),
            }
        }
    }

    impl HeadlessRenderer {
        pub fn new() -> Self {
            Self::default()
        }

        pub fn with_site_config(mut self, site_config: merman_core::MermaidConfig) -> Self {
            self.engine = self.engine.with_site_config(site_config);
            self
        }

        pub fn with_parse_options(mut self, parse: merman_core::ParseOptions) -> Self {
            self.parse = parse;
            self
        }

        pub fn with_strict_parsing(self) -> Self {
            self.with_parse_options(merman_core::ParseOptions::strict())
        }

        pub fn with_lenient_parsing(self) -> Self {
            self.with_parse_options(merman_core::ParseOptions::lenient())
        }

        pub fn with_layout_options(mut self, layout: LayoutOptions) -> Self {
            self.layout = layout;
            self
        }

        pub fn with_svg_options(mut self, svg: SvgRenderOptions) -> Self {
            self.svg = svg;
            self
        }

        pub fn with_diagram_id(mut self, diagram_id: &str) -> Self {
            self.svg.diagram_id = Some(sanitize_svg_id(diagram_id));
            self
        }

        pub fn with_text_measurer(
            mut self,
            measurer: std::sync::Arc<dyn TextMeasurer + Send + Sync>,
        ) -> Self {
            self.layout = self.layout.with_text_measurer(measurer);
            self
        }

        pub fn with_math_renderer(
            mut self,
            renderer: std::sync::Arc<dyn MathRenderer + Send + Sync>,
        ) -> Self {
            self.layout = self.layout.with_math_renderer(renderer.clone());
            self.svg.math_renderer = Some(renderer);
            self
        }

        pub fn with_vendored_text_measurer(self) -> Self {
            self.with_text_measurer(std::sync::Arc::new(
                VendoredFontMetricsTextMeasurer::default(),
            ))
        }

        pub fn with_deterministic_text_measurer(self) -> Self {
            self.with_text_measurer(std::sync::Arc::new(DeterministicTextMeasurer::default()))
        }

        pub fn parse_metadata_sync(
            &self,
            text: &str,
        ) -> Result<Option<merman_core::ParseMetadata>> {
            Ok(self.engine.parse_metadata_sync(text, self.parse)?)
        }

        pub fn parse_diagram_sync(&self, text: &str) -> Result<Option<merman_core::ParsedDiagram>> {
            Ok(self.engine.parse_diagram_sync(text, self.parse)?)
        }

        pub fn layout_diagram_sync(&self, text: &str) -> Result<Option<LayoutedDiagram>> {
            layout_diagram_sync(&self.engine, text, self.parse, &self.layout)
        }

        pub fn render_layouted_svg_sync(&self, diagram: &LayoutedDiagram) -> Result<String> {
            render_layouted_svg(diagram, self.layout.text_measurer.as_ref(), &self.svg)
        }

        pub fn render_layouted_svg_sync_with(
            &self,
            diagram: &LayoutedDiagram,
            svg: &SvgRenderOptions,
        ) -> Result<String> {
            render_layouted_svg(diagram, self.layout.text_measurer.as_ref(), svg)
        }

        pub fn render_svg_sync(&self, text: &str) -> Result<Option<String>> {
            render_svg_sync(&self.engine, text, self.parse, &self.layout, &self.svg)
        }

        /// Renders SVG and applies a best-effort readability fallback for `<foreignObject>` labels.
        ///
        /// Many headless SVG renderers and rasterizers do not fully support HTML inside
        /// `<foreignObject>`. This helper overlays extracted label text as `<text>/<tspan>` so
        /// consumers can still display something readable.
        pub fn render_svg_readable_sync(&self, text: &str) -> Result<Option<String>> {
            let Some(svg) = self.render_svg_sync(text)? else {
                return Ok(None);
            };
            Ok(Some(foreign_object_label_fallback_svg_text(&svg)))
        }

        pub fn render_svg_readable_sync_with_diagram_id(
            &self,
            text: &str,
            diagram_id: &str,
        ) -> Result<Option<String>> {
            let Some(svg) = self.render_svg_sync_with_diagram_id(text, diagram_id)? else {
                return Ok(None);
            };
            Ok(Some(foreign_object_label_fallback_svg_text(&svg)))
        }

        pub fn render_svg_sync_with(
            &self,
            text: &str,
            svg: &SvgRenderOptions,
        ) -> Result<Option<String>> {
            render_svg_sync(&self.engine, text, self.parse, &self.layout, svg)
        }

        pub fn render_svg_sync_with_diagram_id(
            &self,
            text: &str,
            diagram_id: &str,
        ) -> Result<Option<String>> {
            let mut svg = self.svg.clone();
            svg.diagram_id = Some(sanitize_svg_id(diagram_id));
            self.render_svg_sync_with(text, &svg)
        }

        #[cfg(feature = "raster")]
        pub fn render_png_sync(
            &self,
            text: &str,
            raster: &raster::RasterOptions,
        ) -> raster::Result<Option<Vec<u8>>> {
            raster::render_png_sync(
                &self.engine,
                text,
                self.parse,
                &self.layout,
                &self.svg,
                raster,
            )
        }

        #[cfg(feature = "raster")]
        pub fn render_png_sync_with_diagram_id(
            &self,
            text: &str,
            diagram_id: &str,
            raster: &raster::RasterOptions,
        ) -> raster::Result<Option<Vec<u8>>> {
            let mut svg = self.svg.clone();
            svg.diagram_id = Some(sanitize_svg_id(diagram_id));
            raster::render_png_sync(&self.engine, text, self.parse, &self.layout, &svg, raster)
        }

        #[cfg(feature = "raster")]
        pub fn render_jpeg_sync(
            &self,
            text: &str,
            raster: &raster::RasterOptions,
        ) -> raster::Result<Option<Vec<u8>>> {
            raster::render_jpeg_sync(
                &self.engine,
                text,
                self.parse,
                &self.layout,
                &self.svg,
                raster,
            )
        }

        #[cfg(feature = "raster")]
        pub fn render_jpeg_sync_with_diagram_id(
            &self,
            text: &str,
            diagram_id: &str,
            raster: &raster::RasterOptions,
        ) -> raster::Result<Option<Vec<u8>>> {
            let mut svg = self.svg.clone();
            svg.diagram_id = Some(sanitize_svg_id(diagram_id));
            raster::render_jpeg_sync(&self.engine, text, self.parse, &self.layout, &svg, raster)
        }

        #[cfg(feature = "raster")]
        pub fn render_pdf_sync(&self, text: &str) -> raster::Result<Option<Vec<u8>>> {
            raster::render_pdf_sync(&self.engine, text, self.parse, &self.layout, &self.svg)
        }

        #[cfg(feature = "raster")]
        pub fn render_pdf_sync_with_diagram_id(
            &self,
            text: &str,
            diagram_id: &str,
        ) -> raster::Result<Option<Vec<u8>>> {
            let mut svg = self.svg.clone();
            svg.diagram_id = Some(sanitize_svg_id(diagram_id));
            raster::render_pdf_sync(&self.engine, text, self.parse, &self.layout, &svg)
        }
    }
}