merman 0.6.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
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
pub use merman_render::math::{MathRenderer, NoopMathRenderer};
pub use merman_render::model::LayoutedDiagram;
pub use merman_render::svg::{
    CssOverridePolicy, CssOverridePostprocessor, ForeignObjectFallbackPostprocessor,
    SanitizeCssPostprocessor, SanitizeSvgAttributesPostprocessor, ScopedCssPostprocessor,
    StripForeignObjectPostprocessor, SvgPipeline, SvgPipelinePreset, SvgPostprocessContext,
    SvgPostprocessMetadata, SvgPostprocessor, SvgRenderOptions,
    foreign_object_label_fallback_svg_text, resvg_safe_svg,
};
pub use merman_render::text::{
    DeterministicTextMeasurer, TextMeasurer, VendoredFontMetricsTextMeasurer,
};
pub use merman_render::{
    Error as RenderError, LayoutOptions, Result as RenderResult, 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))
}

pub fn apply_svg_pipeline(svg: &str, pipeline: &SvgPipeline) -> Result<String> {
    Ok(pipeline.process_to_string(svg)?)
}

pub fn apply_svg_pipeline_with_metadata(
    svg: &str,
    pipeline: &SvgPipeline,
    metadata: &SvgPostprocessMetadata,
) -> Result<String> {
    Ok(pipeline.process_to_string_with_metadata(svg, metadata)?)
}

pub fn svg_readable(svg: &str) -> Result<String> {
    apply_svg_pipeline(svg, &SvgPipeline::readable())
}

pub fn svg_resvg_safe(svg: &str) -> Result<String> {
    apply_svg_pipeline(svg, &SvgPipeline::resvg_safe())
}

pub fn render_svg_with_pipeline_sync(
    engine: &merman_core::Engine,
    text: &str,
    parse_options: merman_core::ParseOptions,
    layout_options: &LayoutOptions,
    svg_options: &SvgRenderOptions,
    pipeline: &SvgPipeline,
) -> 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,
    )?;
    let metadata = SvgPostprocessMetadata::from_svg(&svg)
        .with_diagram_type(parsed.meta.diagram_type)
        .with_optional_diagram_title(parsed.meta.title);

    Ok(Some(apply_svg_pipeline_with_metadata(
        &svg, pipeline, &metadata,
    )?))
}

/// 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>> {
    render_svg_with_pipeline_sync(
        engine,
        text,
        parse_options,
        layout_options,
        svg_options,
        &SvgPipeline::readable(),
    )
}

pub fn render_svg_resvg_safe_sync(
    engine: &merman_core::Engine,
    text: &str,
    parse_options: merman_core::ParseOptions,
    layout_options: &LayoutOptions,
    svg_options: &SvgRenderOptions,
) -> Result<Option<String>> {
    render_svg_with_pipeline_sync(
        engine,
        text,
        parse_options,
        layout_options,
        svg_options,
        &SvgPipeline::resvg_safe(),
    )
}

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)
}

pub async fn render_svg_with_pipeline(
    engine: &merman_core::Engine,
    text: &str,
    parse_options: merman_core::ParseOptions,
    layout_options: &LayoutOptions,
    svg_options: &SvgRenderOptions,
    pipeline: &SvgPipeline,
) -> 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_with_pipeline_sync(
        engine,
        text,
        parse_options,
        layout_options,
        svg_options,
        pipeline,
    )
}

pub async fn render_svg_resvg_safe(
    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_resvg_safe_sync(engine, text, parse_options, layout_options, svg_options)
}

#[cfg(test)]
mod svg_pipeline_tests {
    use super::*;
    use std::borrow::Cow;

    #[test]
    fn readable_helper_routes_through_readable_pipeline() {
        let engine = merman_core::Engine::new();
        let layout = LayoutOptions::headless_svg_defaults();
        let svg = SvgRenderOptions::default();
        let source = "flowchart TD\nA[Hello] --> B[World]";

        let helper = render_svg_readable_sync(
            &engine,
            source,
            merman_core::ParseOptions::default(),
            &layout,
            &svg,
        )
        .unwrap()
        .unwrap();
        let pipeline = render_svg_with_pipeline_sync(
            &engine,
            source,
            merman_core::ParseOptions::default(),
            &layout,
            &svg,
            &SvgPipeline::readable(),
        )
        .unwrap()
        .unwrap();

        assert_eq!(helper, pipeline);
        assert!(pipeline.contains("data-merman-foreignobject"));
    }

    #[test]
    fn default_svg_helper_stays_parity_without_pipeline_cleanup() {
        let engine = merman_core::Engine::new();
        let layout = LayoutOptions::headless_svg_defaults();
        let svg = SvgRenderOptions::default();
        let source = "flowchart TD\nA[Hello] --> B[World]";

        let default_svg = render_svg_sync(
            &engine,
            source,
            merman_core::ParseOptions::default(),
            &layout,
            &svg,
        )
        .unwrap()
        .unwrap();
        let parity_pipeline = render_svg_with_pipeline_sync(
            &engine,
            source,
            merman_core::ParseOptions::default(),
            &layout,
            &svg,
            &SvgPipeline::parity(),
        )
        .unwrap()
        .unwrap();
        let readable = render_svg_readable_sync(
            &engine,
            source,
            merman_core::ParseOptions::default(),
            &layout,
            &svg,
        )
        .unwrap()
        .unwrap();

        assert_eq!(default_svg, parity_pipeline);
        assert_ne!(default_svg, readable);
    }

    struct MetadataComment;

    impl SvgPostprocessor for MetadataComment {
        fn name(&self) -> &'static str {
            "metadata-comment"
        }

        fn process<'a>(
            &self,
            svg: Cow<'a, str>,
            ctx: &SvgPostprocessContext<'_>,
        ) -> RenderResult<Cow<'a, str>> {
            Ok(Cow::Owned(format!(
                "{}<!--type={};title={};id={}-->",
                svg,
                ctx.diagram_type().unwrap_or(""),
                ctx.diagram_title().unwrap_or(""),
                ctx.svg_id().unwrap_or("")
            )))
        }
    }

    #[test]
    fn render_svg_with_pipeline_passes_parsed_metadata() {
        let renderer = HeadlessRenderer::new().with_diagram_id("host-style");
        let source = "---\ntitle: Host Pipeline\n---\nflowchart TD\nA --> B";
        let pipeline = SvgPipeline::parity().with_postprocessor(MetadataComment);

        let svg = renderer
            .render_svg_with_pipeline_sync(source, &pipeline)
            .unwrap()
            .unwrap();

        assert!(svg.contains("type=flowchart"));
        assert!(svg.contains("title=Host Pipeline"));
        assert!(svg.contains("id=host-style"));
    }
}

/// 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)
    }

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

    /// 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>> {
        self.render_svg_with_pipeline_sync(text, &SvgPipeline::readable())
    }

    pub fn render_svg_resvg_safe_sync(&self, text: &str) -> Result<Option<String>> {
        self.render_svg_with_pipeline_sync(text, &SvgPipeline::resvg_safe())
    }

    pub fn render_svg_readable_sync_with_diagram_id(
        &self,
        text: &str,
        diagram_id: &str,
    ) -> Result<Option<String>> {
        self.render_svg_with_pipeline_sync_with_diagram_id(
            text,
            diagram_id,
            &SvgPipeline::readable(),
        )
    }

    pub fn render_svg_resvg_safe_sync_with_diagram_id(
        &self,
        text: &str,
        diagram_id: &str,
    ) -> Result<Option<String>> {
        self.render_svg_with_pipeline_sync_with_diagram_id(
            text,
            diagram_id,
            &SvgPipeline::resvg_safe(),
        )
    }

    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_with_pipeline_sync_with(
        &self,
        text: &str,
        svg: &SvgRenderOptions,
        pipeline: &SvgPipeline,
    ) -> Result<Option<String>> {
        render_svg_with_pipeline_sync(&self.engine, text, self.parse, &self.layout, svg, pipeline)
    }

    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)
    }

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

    #[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)
    }
}