mrk-cli 0.12.0

Render Markdown beautifully in the terminal: syntax highlighting, tables, themes, and Mermaid diagrams as images.
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
use std::collections::{HashMap, HashSet};
use std::sync::Arc;

use mermaid_rs_renderer::{DiagramKind, Edge, Graph};

use super::DiagramError;
use super::catch::caught;
use super::{kind, label};

/// Mermaid blocks above this size are shown as source.
pub const MAX_SOURCE_BYTES: usize = 64 * 1024;
/// The limits below keep the slowest diagram measured within them under the times `specs/02-security.md` rule 4 gives.
const MAX_LINKS: usize = 150;
const MAX_MESSAGES: usize = 400;
const MAX_ELEMENTS: usize = 600;
/// vt-mermaid refuses more, after reading the source up to the first edge over.
const MAX_EDGES: usize = vt_mermaid::MAX_EDGES;
/// Every row of a sequence crosses all its participants, of a git graph all its branches: a picture of more than this
/// many would be shrunk past reading, and vt-mermaid draws at most 50 participants.
const MAX_LANES: usize = 200;
/// What a document's diagrams may cost together, in milliseconds of layout at the slowest rate measured for what
/// each one counts; a diagram that does not fit what is left shows as source.
pub const MAX_DOCUMENT_COST_MS: usize = 12_000;
/// What any diagram costs at least, its fixed work aside from the layout: at most this many diagrams fit a document.
const MIN_COST_MS: usize = 5;
/// The most diagrams a document lays out.
pub const MAX_DOCUMENT_DIAGRAMS: usize = MAX_DOCUMENT_COST_MS / MIN_COST_MS;
/// What a picture costs on top of its layout: fitting and drawing it.
const PICTURE_COST_MS: usize = 20;
/// What vt-mermaid's text costs on top of a graph's edges, and what a sequence costs: 990 messages across 50
/// participants took 33 ms.
const TEXT_COST_MS: usize = 60;
/// What a graph as text costs at most: vt-mermaid's layout and routing budget of 6 million steps took at most 0.5 s.
const MAX_TEXT_COST_MS: usize = 500;
/// An edge walled in is searched for over the whole grid, so few edges may take long: 8 took 113 ms, 24 took 240 ms.
const TEXT_EDGE_COST_MS: usize = 8;

/// What a diagram's layout time grows with, counted before an engine lays it out.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Load {
    /// Nodes, edges, edge labels, subgraphs, state notes, and every edge doubling another between the same two nodes,
    /// once per earlier one: what the layered layout routes around.
    Links,
    /// Participants, messages, notes and frame parts of a sequence diagram.
    Messages,
    /// Nodes, edges, subgraphs, commits, C4 shapes and relations, and chart marks, for the diagrams laid out in rows or
    /// rings.
    Elements,
    /// Edges of a flowchart, class, state, ER, block or architecture diagram, which vt-mermaid routes on a grid:
    /// `a & b --> c & d` is four.
    Edges,
    /// Participants of a sequence diagram or branches of a git graph, the columns every row crosses.
    Lanes,
}

impl Load {
    pub fn limit(self) -> usize {
        match self {
            Self::Links => MAX_LINKS,
            Self::Messages => MAX_MESSAGES,
            Self::Elements => MAX_ELEMENTS,
            Self::Edges => MAX_EDGES,
            Self::Lanes => MAX_LANES,
        }
    }

    pub fn unit(self) -> &'static str {
        match self {
            Self::Links => "links",
            Self::Messages => "messages",
            Self::Elements => "elements",
            Self::Edges => "edges",
            Self::Lanes => "participants or branches",
        }
    }

    /// The slowest layout measured for that many, in milliseconds: the layered engines slow down per unit as the
    /// diagram grows (145 links between random nodes took 3.1 s, 51 took 0.27 s), the row-by-row ones do not.
    fn cost_ms(self, count: usize) -> usize {
        match self {
            Self::Links => count * count / 7,
            Self::Edges => (TEXT_COST_MS + count * TEXT_EDGE_COST_MS).min(MAX_TEXT_COST_MS),
            Self::Messages | Self::Elements | Self::Lanes => count,
        }
    }

    fn within(self, count: usize) -> Result<usize, DiagramError> {
        if count > self.limit() { Err(DiagramError::OverBudget(self)) } else { Ok(self.cost_ms(count)) }
    }
}

/// A diagram cleaned and parsed once, with what each engine's count says of it: layout time grows much faster than
/// the source, which its 64 KiB cap alone does not bound.
pub struct Diagram {
    /// The source with its labels cleaned for vt-mermaid, which draws their emphasis.
    text_source: Arc<str>,
    /// mermaid-rs-renderer's graph and what it costs as a picture, or why the picture is refused.
    picture: Result<(Arc<Graph>, usize), DiagramError>,
    /// What it costs as vt-mermaid's text, or why the text is refused.
    text: Result<usize, DiagramError>,
}

impl Diagram {
    /// Refuses, for both engines and before parsing, a block too large to read or naming too many lanes, counted on the
    /// cleaned labels.
    pub fn new(source: &str) -> Result<Self, DiagramError> {
        sized(source)?;
        let cleaned = label::clean(source);
        readable(&cleaned)?;
        let graph = parsed(&cleaned);
        let text = text_cost(&cleaned, graph.as_ref().ok());
        let picture = graph.and_then(|graph| picture_cost(&graph).map(|cost| (Arc::new(graph), cost)));
        Ok(Self { text_source: label::clean_for_text(source).into(), picture, text })
    }

    pub fn text_source(&self) -> Arc<str> {
        Arc::clone(&self.text_source)
    }

    /// The graph to lay out as a picture, unless its count refuses one.
    pub fn picture_graph(&self) -> Result<Arc<Graph>, DiagramError> {
        self.picture.as_ref().map(|(graph, _)| Arc::clone(graph)).map_err(Clone::clone)
    }

    /// Refuses what vt-mermaid would take too long to lay out: counted on mermaid-rs-renderer's graph when it parses
    /// the diagram, else on a scan of the source, since vt-mermaid reads syntax mermaid-rs-renderer refuses.
    pub fn admit_text(&self) -> Result<(), DiagramError> {
        self.text.as_ref().map(|_| ()).map_err(Clone::clone)
    }

    /// What drawing it costs its document: as a picture when pictures are drawn and its count allows one, else as
    /// text; at least `MIN_COST_MS`, even when both counts refuse it, since parsing it took time.
    pub fn cost(&self, pictures: bool) -> usize {
        let picture = self.picture.as_ref().ok().filter(|_| pictures).map(|(_, cost)| cost + PICTURE_COST_MS);
        picture.or_else(|| self.text.as_ref().ok().copied()).map_or(MIN_COST_MS, |cost| cost.max(MIN_COST_MS))
    }
}

/// The diagrams of one document its budget lets through, in reading order, each distinct source counted once since
/// the cache keeps what a repeated one costs: each that fits what is left of the budget, none read once nothing can
/// fit. A block refused before parsing costs nothing and keeps its refusal.
pub struct Allowance(HashMap<String, Result<Diagram, DiagramError>>);

impl Allowance {
    pub fn new(sources: impl IntoIterator<Item = String>, pictures: bool) -> Self {
        let mut diagrams = HashMap::new();
        let mut left = MAX_DOCUMENT_COST_MS;
        let mut sources = sources.into_iter();
        while left >= MIN_COST_MS
            && let Some(source) = sources.next()
        {
            if diagrams.contains_key(&source) {
                continue;
            }
            let diagram = Diagram::new(&source);
            let cost = diagram.as_ref().map_or(0, |diagram| diagram.cost(pictures));
            let admitted = if cost <= left {
                left -= cost;
                diagram
            } else {
                Err(DiagramError::OverDocumentBudget)
            };
            diagrams.insert(source, admitted);
        }
        Self(diagrams)
    }

    pub fn admit(&self, source: &str) -> Result<&Diagram, DiagramError> {
        self.0.get(source).ok_or(DiagramError::OverDocumentBudget)?.as_ref().map_err(Clone::clone)
    }
}

fn parsed(source: &str) -> Result<Graph, DiagramError> {
    if !kind::is_known(source) {
        return Err(DiagramError::UnknownKind);
    }
    let parsed = caught(|| mermaid_rs_renderer::parse_mermaid_strict(source))?.map_err(|error| DiagramError::invalid(&error))?;
    Ok(parsed.graph)
}

fn sized(source: &str) -> Result<(), DiagramError> {
    if source.len() > MAX_SOURCE_BYTES { Err(DiagramError::Oversized) } else { Ok(()) }
}

fn readable(source: &str) -> Result<(), DiagramError> {
    Load::Lanes.within(scanned_lanes(source)).map(|_| ())
}

fn picture_cost(graph: &Graph) -> Result<usize, DiagramError> {
    let (load, count) = picture_load(graph);
    load.within(count)
}

/// vt-mermaid spends nearly all its time routing the edges of a graph kind, draws a sequence row after row, and refuses
/// any other kind at once.
fn text_cost(source: &str, graph: Option<&Graph>) -> Result<usize, DiagramError> {
    let edges = graph.map_or_else(|| scanned_edges(source), graph_edges);
    edges.map_or(Ok(MIN_COST_MS), |edges| Load::Edges.within(edges))
}

fn picture_load(graph: &Graph) -> (Load, usize) {
    let shapes = graph.nodes.len() + graph.edges.len() + graph.subgraphs.len();
    match graph.kind {
        DiagramKind::Flowchart
        | DiagramKind::Class
        | DiagramKind::State
        | DiagramKind::Er
        | DiagramKind::Requirement
        | DiagramKind::Architecture => (Load::Links, shapes + labels(&graph.edges) + doublings(&graph.edges) + graph.state_notes.len()),
        DiagramKind::Sequence | DiagramKind::ZenUML => {
            (Load::Messages, graph.nodes.len() + graph.edges.len() + graph.sequence_notes.len() + frame_parts(graph))
        }
        _ => (Load::Elements, shapes + graph.gitgraph.commits.len() + graph.c4.shapes.len() + graph.c4.rels.len() + chart_marks(graph)),
    }
}

/// Each part of a sequence frame: an `alt` with one `else` is two.
fn frame_parts(graph: &Graph) -> usize {
    graph.sequence_frames.iter().map(|frame| frame.sections.len()).sum()
}

/// What the chart parsers keep outside the nodes: pie slices, timeline periods and their events, and xy chart
/// categories, series and their values.
fn chart_marks(graph: &Graph) -> usize {
    let timeline: usize = graph.timeline.events.iter().map(|period| 1 + period.events.len()).sum();
    let series: usize = graph.xychart.series.iter().map(|series| 1 + series.values.len()).sum();
    graph.pie_slices.len() + timeline + graph.xychart.x_axis_categories.len() + series
}

/// The edges vt-mermaid routes: those of a graph kind, none for a sequence, `None` for a kind it does not draw.
fn graph_edges(graph: &Graph) -> Option<usize> {
    match graph.kind {
        DiagramKind::Flowchart
        | DiagramKind::Class
        | DiagramKind::State
        | DiagramKind::Er
        | DiagramKind::Block
        | DiagramKind::Architecture => Some(graph.edges.len()),
        DiagramKind::Sequence => Some(0),
        _ => None,
    }
}

/// The edges vt-mermaid routes as `graph_edges` counts them, the keyword read by prefix with case ignored, so the
/// count covers every source vt-mermaid reads as that kind.
fn scanned_edges(source: &str) -> Option<usize> {
    let keyword = kind::header(source)?.to_ascii_lowercase();
    let opens_on = |kinds: &[&str]| kinds.iter().any(|kind| keyword.starts_with(kind));
    if opens_on(&["sequencediagram"]) {
        return Some(0);
    }
    let arrows: &[&str] = if opens_on(&["classdiagram", "erdiagram"]) {
        &DOTTED_ARROWS
    } else if opens_on(&["graph", "flowchart", "statediagram", "block", "architecture"]) {
        &ARROWS
    } else {
        return None;
    };
    Some(statements(source).skip(1).map(|statement| edges_in(&statement, arrows)).sum())
}

/// mermaid-rs-renderer's parser looks each participant or branch up among those already met, so its time grows with
/// the square of the lanes: a scan counts the names first, those a message or a declaration gives, `participant A as Alice` being `A`
/// and a git graph starting on `main`.
fn scanned_lanes(source: &str) -> usize {
    let keyword = kind::header(source).and_then(|header| header.split_whitespace().next()).unwrap_or_default().to_ascii_lowercase();
    let names: HashSet<String> = if keyword.starts_with("sequencediagram") {
        statements(source).skip(1).flat_map(|statement| participants(&statement)).collect()
    } else if keyword.starts_with("gitgraph") {
        statements(source).filter_map(|statement| declared(&statement, &["branch"])).chain(["main".to_owned()]).collect()
    } else {
        HashSet::new()
    };
    names.len()
}

/// The participants a sequence statement names: the one it declares, or those either side of a message's arrows.
fn participants(statement: &str) -> Vec<String> {
    if let Some(name) = declared(statement.trim_start_matches("create "), &["participant", "actor"]) {
        return vec![name];
    }
    let before_text = statement.split_once(':').map_or(statement, |(before, _)| before);
    let sides = sides(before_text, &SEQUENCE_ARROWS);
    if sides.len() < 2 {
        return Vec::new();
    }
    sides.iter().map(|side| side.trim().trim_start_matches(['+', '-']).to_owned()).filter(|name| !name.is_empty()).collect()
}

/// The word after the keyword a statement opens on, when it is one of `keywords`.
fn declared(statement: &str, keywords: &[&str]) -> Option<String> {
    let mut words = statement.split_whitespace();
    let keyword = words.next()?;
    if keywords.iter().any(|candidate| candidate.eq_ignore_ascii_case(keyword)) { words.next().map(str::to_owned) } else { None }
}

/// Longest first, so a shorter arrow never splits a longer one.
const SEQUENCE_ARROWS: [&str; 10] = ["<<-->>", "<<->>", "-->>", "->>", "-->", "->", "--x", "-x", "--)", "-)"];
const ARROWS: [&str; 3] = ["--", "==", "-."];
const DOTTED_ARROWS: [&str; 2] = ["--", ".."];
const ARROW_MARK: char = '\u{0}';

/// One edge per pair of nodes either side of each arrow: `a & b --> c & d --> e` is four then two.
fn edges_in(statement: &str, arrows: &[&str]) -> usize {
    let nodes: Vec<usize> = sides(statement, arrows).iter().map(|side| side.split('&').count()).collect();
    nodes.windows(2).map(|pair| pair[0] * pair[1]).sum()
}

/// The text between the arrows of a statement, `arrows` matched in their order.
fn sides(statement: &str, arrows: &[&str]) -> Vec<String> {
    let marked = arrows.iter().fold(statement.to_owned(), |marked, arrow| marked.replace(arrow, &ARROW_MARK.to_string()));
    marked.split(ARROW_MARK).map(str::to_owned).collect()
}

/// The statements of a diagram: split on newlines and semicolons, with every carriage return deleted.
fn statements(source: &str) -> impl Iterator<Item = String> {
    let statements: Vec<String> = source
        .replace('\r', "")
        .split(['\n', ';'])
        .map(str::trim)
        .filter(|statement| !statement.is_empty() && !statement.starts_with("%%"))
        .map(str::to_owned)
        .collect();
    statements.into_iter()
}

fn labels(edges: &[Edge]) -> usize {
    edges.iter().flat_map(|edge| [&edge.label, &edge.start_label, &edge.end_label]).filter(|label| label.is_some()).count()
}

/// Edges between the same two nodes route and label around each other, so each costs one more per edge before it.
fn doublings(edges: &[Edge]) -> usize {
    let mut seen: HashMap<(&str, &str), usize> = HashMap::new();
    edges
        .iter()
        .map(|edge| {
            let pair = if edge.from <= edge.to { (edge.from.as_str(), edge.to.as_str()) } else { (edge.to.as_str(), edge.from.as_str()) };
            let earlier = seen.entry(pair).or_default();
            *earlier += 1;
            *earlier - 1
        })
        .sum()
}

#[cfg(test)]
mod tests {
    #![allow(clippy::unwrap_used, clippy::expect_used)]

    use super::*;

    fn edges(count: usize, edge: impl Fn(usize) -> String) -> String {
        format!("graph TD\n{}", (0..count).map(|index| format!("  {}\n", edge(index))).collect::<String>())
    }

    fn chain(count: usize, name: &str) -> String {
        edges(count, |index| format!("{name}{index} --> {name}{}", index + 1))
    }

    /// A sequence of `count` participants, each named by a message.
    fn messaged(count: usize) -> String {
        format!("sequenceDiagram\n{}", (1..count).map(|index| format!("  p{} ->> p{index}: m\n", index - 1)).collect::<String>())
    }

    fn boxed(count: usize) -> String {
        messaged(count).replace("sequenceDiagram\n", "sequenceDiagram\n  box Front\n    participant p0\n  end\n")
    }

    /// A git graph of `count` branches, `main` included.
    fn branched(count: usize) -> String {
        format!("gitGraph\n{}", (1..count).map(|index| format!("  branch b{index}\n  commit\n")).collect::<String>())
    }

    fn graph(source: &str) -> Graph {
        mermaid_rs_renderer::parse_mermaid(source).unwrap().graph
    }

    fn load_of(source: &str) -> (Load, usize) {
        picture_load(&graph(source))
    }

    fn picture_graph(source: &str) -> Result<Arc<Graph>, DiagramError> {
        Diagram::new(source)?.picture_graph()
    }

    fn admit_text(source: &str) -> Result<(), DiagramError> {
        Diagram::new(source)?.admit_text()
    }

    fn cost(source: &str, pictures: bool) -> usize {
        Diagram::new(source).map_or(0, |diagram| diagram.cost(pictures))
    }

    fn admitted(allowance: &Allowance, sources: &[String]) -> Vec<bool> {
        sources.iter().map(|source| allowance.admit(source).is_ok()).collect()
    }

    #[test]
    fn a_diagram_costs_what_the_engine_that_draws_it_counts() {
        let flowchart = chain(40, "a");

        assert_eq!(cost(&flowchart, true), Load::Links.cost_ms(41 + 40) + PICTURE_COST_MS);
        assert_eq!(cost(&flowchart, false), Load::Edges.cost_ms(40));
        assert_eq!(cost(&format!("sequenceDiagram\n{}", "  a ->> b: hi\n".repeat(1000)), false), TEXT_COST_MS);
        assert_eq!(cost("pie\n  \"a\" : 1", false), MIN_COST_MS);
    }

    #[test]
    fn a_graph_as_text_costs_what_its_walled_in_edges_may_take() {
        assert_eq!(cost(&chain(8, "a"), false), TEXT_COST_MS + 8 * TEXT_EDGE_COST_MS);
        assert_eq!(cost(&chain(MAX_EDGES, "a"), false), MAX_TEXT_COST_MS);
    }

    #[test]
    fn a_diagram_both_engines_refuse_costs_little() {
        assert_eq!(cost(&chain(200, "a"), true), MIN_COST_MS);
        assert_eq!(cost(&"%%\n".repeat(MAX_SOURCE_BYTES), true), 0);
    }

    #[test]
    fn each_diagram_that_fits_what_is_left_of_the_budget_is_let_through_in_reading_order() {
        let large = |name: &str| chain(40, name);
        let large_cost = cost(&large("a"), false);
        let fitting = MAX_DOCUMENT_COST_MS / large_cost;
        let sources: Vec<String> = (0..=fitting).map(|index| large(&format!("d{index}_"))).chain([chain(1, "small")]).collect();

        let allowance = Allowance::new(sources.clone(), false);

        let expected: Vec<bool> = (0..=fitting).map(|index| index < fitting).chain([true]).collect();
        assert_eq!(admitted(&allowance, &sources), expected);
        assert_eq!(allowance.admit(&large("z")).err(), Some(DiagramError::OverDocumentBudget));
    }

    #[test]
    fn a_repeated_diagram_costs_its_document_once() {
        let large = chain(MAX_EDGES, "a");
        let repeats = MAX_DOCUMENT_COST_MS / cost(&large, false) + 1;
        let last = chain(MAX_EDGES, "b");

        let allowance = Allowance::new(std::iter::repeat_n(large.clone(), repeats).chain([last.clone()]), false);

        assert_eq!(admitted(&allowance, &[large, last]), [true, true]);
    }

    #[test]
    fn a_document_lets_through_at_most_its_diagram_count() {
        let allowance = Allowance::new((0..2 * MAX_DOCUMENT_DIAGRAMS).map(|index| format!("pie\n  \"n{index}\" : 1")), false);

        assert_eq!(allowance.0.values().filter(|diagram| diagram.is_ok()).count(), MAX_DOCUMENT_DIAGRAMS);
    }

    #[test]
    fn a_spent_budget_reads_no_further_diagram() {
        let spending = (0..MAX_DOCUMENT_DIAGRAMS).map(|index| format!("pie\n  \"n{index}\" : 1"));
        let unread = std::iter::from_fn(|| -> Option<String> { panic!("a diagram read after the budget was spent") });

        let allowance = Allowance::new(spending.chain(unread), false);

        assert_eq!(allowance.0.values().filter(|diagram| diagram.is_ok()).count(), MAX_DOCUMENT_DIAGRAMS);
    }

    #[test]
    fn diagrams_parsed_then_refused_by_both_counts_still_spend_the_budget() {
        let refused = (0..MAX_DOCUMENT_DIAGRAMS).map(|index| chain(MAX_EDGES + 1, &format!("d{index}_")));
        let unread = std::iter::from_fn(|| -> Option<String> { panic!("a diagram read after the budget was spent") });

        let allowance = Allowance::new(refused.chain(unread), false);

        assert_eq!(allowance.0.len(), MAX_DOCUMENT_DIAGRAMS);
    }

    #[test]
    fn invalid_source_is_an_error() {
        assert!(matches!(picture_graph("graph TD\n  A -->"), Err(DiagramError::Invalid(_))));
    }

    #[test]
    fn a_kind_mrk_does_not_know_never_reaches_the_picture_parser() {
        assert_eq!(picture_graph("roadmap-beta\n  step one").err(), Some(DiagramError::UnknownKind));
        assert_eq!(picture_graph("hello").err(), Some(DiagramError::UnknownKind));
        assert_eq!(picture_graph("blocks-beta\n  a").err(), Some(DiagramError::UnknownKind));
    }

    #[test]
    fn a_parser_panic_is_a_crash_costing_what_the_text_counts() {
        let panicking = "architecture-beta\n group )g(cloud)[G]";

        assert_eq!(picture_graph(panicking).unwrap_err(), DiagramError::Crashed);
        assert_eq!(cost(panicking, true), Load::Edges.cost_ms(0));
    }

    #[test]
    fn oversized_source_is_refused_before_parsing() {
        assert_eq!(sized(&"%%\n".repeat(MAX_SOURCE_BYTES)), Err(DiagramError::Oversized));
    }

    #[test]
    fn nodes_edges_labels_subgraphs_and_doubled_edges_are_links() {
        assert_eq!(load_of("graph TD\n  a --> b\n  b --> c"), (Load::Links, 3 + 2));
        assert_eq!(load_of("graph TD\n  a -->|yes| b"), (Load::Links, 2 + 1 + 1));
        assert_eq!(load_of("graph TD\n  subgraph s\n  a --> b\n  end"), (Load::Links, 2 + 1 + 1));
        assert_eq!(load_of("graph TD\n  a --> b\n  b --> a\n  a --> b"), (Load::Links, 2 + 3 + (1 + 2)));
        assert_eq!(load_of("graph TD\n  a & b --> c & d"), (Load::Links, 4 + 4));
        assert_eq!(load_of("classDiagram\n  A --> B").0, Load::Links);
    }

    #[test]
    fn each_kind_counts_what_its_layout_grows_with() {
        assert_eq!(load_of("sequenceDiagram\n  a ->> b: hi\n  b ->> a: ho\n  note over a: x"), (Load::Messages, 2 + 2 + 1));
        assert_eq!(load_of("pie\n  \"a\" : 1").0, Load::Elements);
        assert_eq!(load_of("packet-beta\n  0-15: \"Source\"").0, Load::Elements);
        assert_eq!(load_of("gitGraph\n  commit\n  commit"), (Load::Elements, 2));
    }

    #[test]
    fn what_a_parser_keeps_outside_nodes_and_edges_counts_too() {
        assert_eq!(load_of("pie\n  \"a\" : 1\n  \"b\" : 2"), (Load::Elements, 2));
        assert_eq!(load_of("timeline\n  2001 : a : b\n  2002 : c"), (Load::Elements, 2 + 3));
        assert_eq!(load_of("xychart-beta\n  x-axis [a, b]\n  bar [1, 2]\n  line [3, 4]"), (Load::Elements, 2 + 2 * (1 + 2)));
        assert_eq!(load_of("sequenceDiagram\n  alt x\n  a ->> b: hi\n  else y\n  a ->> b: ho\n  end"), (Load::Messages, 2 + 2 + 2));
        assert_eq!(load_of("stateDiagram-v2\n  a --> b\n  note right of a : n\n  note left of b : m"), (Load::Links, 2 + 1 + 2));
    }

    #[test]
    fn a_chart_over_its_count_is_refused_as_a_picture() {
        let pie = format!("pie\n{}", (0..=MAX_ELEMENTS).map(|index| format!("  \"s{index}\" : 1\n")).collect::<String>());

        assert_eq!(picture_graph(&pie).err(), Some(DiagramError::OverBudget(Load::Elements)));
    }

    #[test]
    fn a_diagram_at_its_limit_passes_and_one_more_is_refused() {
        assert!(picture_graph(&chain(MAX_LINKS / 2 - 1, "n")).is_ok());
        assert_eq!(picture_graph(&chain(MAX_LINKS / 2 + 1, "n")).unwrap_err(), DiagramError::OverBudget(Load::Links));
    }

    #[test]
    fn parallel_labelled_edges_exhaust_the_budget_quickly() {
        let parallel = edges(30, |_| "a -->|again| b".to_owned());

        assert_eq!(load_of(&parallel), (Load::Links, 2 + 30 + 30 + (0..30).sum::<usize>()));
        assert_eq!(picture_graph(&parallel).unwrap_err(), DiagramError::OverBudget(Load::Links));
    }

    #[test]
    fn the_text_engine_counts_the_parsed_edges_of_a_graph_kind() {
        assert_eq!(graph_edges(&graph("graph TD\n  a --> b --> c\n  d; e")), Some(2));
        assert_eq!(graph_edges(&graph("graph TD\n  a & b & c --> d & e & f")), Some(9));
        assert_eq!(graph_edges(&graph("erDiagram\n  A ||--o{ B : has")), Some(1));
        assert_eq!(graph_edges(&graph("block-beta\n  a b c\n  a --> b\n  b --> c")), Some(2));
        assert_eq!(graph_edges(&graph("architecture-beta\n  service a(server)[A]\n  service b(disk)[B]\n  a:R --> L:b")), Some(1));
        assert_eq!(graph_edges(&graph("sequenceDiagram\n  a ->> b: hi")), Some(0));
        assert_eq!(graph_edges(&graph("pie\n  \"a\" : 1")), None);
        assert_eq!(admit_text(&chain(MAX_EDGES, "n")), Ok(()));
        assert_eq!(admit_text(&chain(MAX_EDGES + 1, "n")), Err(DiagramError::OverBudget(Load::Edges)));
    }

    #[test]
    fn block_and_architecture_diagrams_at_the_edge_limit_pass_and_one_more_is_refused() {
        fn block(count: usize) -> String {
            format!("block-beta\n{}", (0..count).map(|index| format!("  n{index} --> n{}\n", index + 1)).collect::<String>())
        }
        fn architecture(count: usize) -> String {
            let services: String = (0..=count).map(|index| format!("  service n{index}(server)[N]\n")).collect();
            let edges: String = (0..count).map(|index| format!("  n{index}:R --> L:n{}\n", index + 1)).collect();
            format!("architecture-beta\n{services}{edges}")
        }

        for diagram in [block, architecture] {
            assert_eq!(admit_text(&diagram(MAX_EDGES)), Ok(()));
            assert_eq!(admit_text(&diagram(MAX_EDGES + 1)), Err(DiagramError::OverBudget(Load::Edges)));
        }
    }

    #[test]
    fn the_scan_for_syntax_mermaid_rs_renderer_refuses_counts_every_fanned_out_edge() {
        assert_eq!(scanned_edges("graph TD\n  a --> b --> c\n  %% a comment\n  d; e"), Some(2));
        assert_eq!(scanned_edges("graph TD\n  a & b & c --> d & e --> f"), Some(3 * 2 + 2));
        assert_eq!(scanned_edges(&format!("sequenceDiagram\n{}", "  a ->> b: hi\n".repeat(1000))), Some(0));
        assert_eq!(scanned_edges("pie\n  \"a--b\" : 1"), None);
        assert_eq!(scanned_edges("block-beta\n  a b\n  a --> b"), Some(1));
        assert_eq!(scanned_edges("architecture-beta\n  service a(server)[A]\n  a:L -- R:b\n  a:T --> B:c"), Some(2));
        assert_eq!(scanned_edges("%% why\nclassDiagram\n  class A {\n    +f() int\n  }\n  A & C --> B\n  B ..> C"), Some(3));
    }

    #[test]
    fn fanned_out_edges_hidden_on_one_line_are_refused_by_both_engines() {
        let fanned = edges(17, |index| format!("a{index} & b{index} & c{index} --> d{index} & e{index} & f{index}"));

        assert_eq!(picture_graph(&fanned).unwrap_err(), DiagramError::OverBudget(Load::Links));
        assert_eq!(admit_text(&fanned), Err(DiagramError::OverBudget(Load::Edges)));
    }

    #[test]
    fn lanes_over_the_limit_are_refused_before_parsing() {
        fn declared(count: usize) -> String {
            format!("sequenceDiagram\n{}", (0..count).map(|index| format!("  actor p{index} as Person {index}\n")).collect::<String>())
        }
        fn fronted(count: usize) -> String {
            format!("---\ntitle: Lanes\n---\n{}", messaged(count))
        }

        for lanes in [messaged, boxed, branched, declared, fronted] {
            assert_eq!(readable(&lanes(MAX_LANES)), Ok(()));
            assert_eq!(readable(&lanes(MAX_LANES + 1)), Err(DiagramError::OverBudget(Load::Lanes)));
        }
    }

    #[test]
    fn the_lane_scan_counts_each_participant_once_whatever_names_it() {
        let source = "sequenceDiagram\n  autonumber\n  create participant A\n  actor U as User\n  U->>+A: hi\n  A-->>-U: ok\n  \
                      A-)B: async\n  B--xU: lost\n  U<<->>A: both\n  note over A,B: n\n  loop every minute\n  A->>A: tick\n  end";

        assert_eq!(scanned_lanes(source), 3);
        assert_eq!(scanned_lanes("gitGraph\n  commit\n  branch dev\n  checkout main\n  branch dev"), 2);
        assert_eq!(scanned_lanes(&chain(MAX_LANES + 1, "n")), 0);
    }

    #[test]
    fn syntax_mermaid_rs_renderer_refuses_passes_the_text_gate() {
        assert_eq!(admit_text("classDiagram\n  class Shape {\n    <<interface>>\n    +area() double\n  }"), Ok(()));
    }
}