From 30214799422d10434f499d518ada9202f69a2f2c Mon Sep 17 00:00:00 2001 From: Naohiro CHIKAMATSU Date: Wed, 12 Aug 2026 09:19:34 +0900 Subject: [PATCH 1/2] feat(mermaid): add C4 context diagram support mermaid/c4 builds the C4Context diagram: the people and the software systems around the one being described. Scope stays there on purpose, because mermaid marks its C4 support experimental and says the syntax may change; C4Container, C4Component, C4Dynamic, C4Deployment and the UpdateElementStyle family can each arrive later as a new method without changing anything that exists. A boundary is a pair of calls rather than a callback taking a nested builder: Boundary, EnterpriseBoundary and SystemBoundary open one and BoundaryEnd closes it, the way mermaid/treemap walks its own nesting with Section and Parent. A boundary left open is reported from Build, because mermaid refuses a diagram whose brace never closes and the whole drawing is lost. The escaping was measured against the renderer rather than reasoned about, and neither escape that looks obvious works. A backslash makes mermaid refuse the diagram; doubling the quote silently splits the argument, so Rel(a, b, "x""y") draws "y" as the technology rather than as part of the label. What C4 implements is its own entity form, so a quote becomes "#quot;" and a "#" becomes "#35;" ahead of it, or a label holding "#quot;" would come back as a character the caller never wrote. The title is the one place the text is unquoted: mermaid takes the rest of the line, quotes included, so quoting it would draw the quotation marks, and the escaped pair there is "#" and ";" instead. The render check learned to decode those escapes. It compares a declared title against the drawing, and mermaid decodes "#35;" before drawing it, so without this an escaped title reads as missing. Two fixtures pin both halves: one that must pass and one whose title really is lost. Closes #128 --- README.md | 91 ++++ SPEC.md | 2 +- contract_test.go | 11 + doc/c4/generated.md | 17 + doc/c4/main.go | 50 ++ doc/edgecase/c4.md | 22 + doc/edgecase/main.go | 27 + mermaid/c4/c4.go | 458 +++++++++++++++++ mermaid/c4/c4_test.go | 464 ++++++++++++++++++ mermaid/c4/config.go | 100 ++++ mermaid/c4/examples_test.go | 99 ++++ mermaid/c4/testdata/golden/c4.md | 21 + scripts/mermaid-check/check.mjs | 25 +- scripts/mermaid-check/selftest.mjs | 8 + .../testdata/c4-escaped-title.mdfixture | 14 + .../testdata/c4-title-line-break.mdfixture | 13 + 16 files changed, 1420 insertions(+), 2 deletions(-) create mode 100644 doc/c4/generated.md create mode 100644 doc/c4/main.go create mode 100644 doc/edgecase/c4.md create mode 100644 mermaid/c4/c4.go create mode 100644 mermaid/c4/c4_test.go create mode 100644 mermaid/c4/config.go create mode 100644 mermaid/c4/examples_test.go create mode 100644 mermaid/c4/testdata/golden/c4.md create mode 100644 scripts/mermaid-check/testdata/c4-escaped-title.mdfixture create mode 100644 scripts/mermaid-check/testdata/c4-title-line-break.mdfixture diff --git a/README.md b/README.md index 18f1e7b..58458fe 100644 --- a/README.md +++ b/README.md @@ -62,6 +62,7 @@ Anything that would make the library complicated, such as generating nested list - [x] mermaid treemap diagram - [x] mermaid radar chart - [x] mermaid sankey diagram +- [x] mermaid C4 context diagram (experimental feature) ### Features not in Markdown syntax - Generate badges; RedBadge(), YellowBadge(), GreenBadge(). @@ -2137,6 +2138,96 @@ treemap-beta "Ads": 800 ``` +### C4 context syntax + +mermaid marks its C4 support experimental and says the syntax may change, so this package stays on the C4Context diagram: the people and the software systems around the one being described. + +```go +package main + +import ( + "io" + "os" + + "github.com/nao1215/markdown" + "github.com/nao1215/markdown/mermaid/c4" +) + +//go:generate go run main.go + +func main() { + f, err := os.Create("generated.md") + if err != nil { + panic(err) + } + defer f.Close() + + diagram := c4.NewDiagram(io.Discard, c4.WithTitle("System Context: Internet Banking")). + EnterpriseBoundary("bank", "Big Bank plc"). + Person("customer", "Personal Banking Customer", c4.WithDescription("A customer of the bank.")). + SystemBoundary("banking", "Internet Banking"). + System("web", "Internet Banking System", c4.WithDescription("Shows account information.")). + SystemDb("accounts", "Accounts Database"). + BoundaryEnd(). + BoundaryEnd(). + SystemExt("mail", "E-mail System", c4.WithDescription("The internal Microsoft Exchange system.")). + Rel("customer", "web", "Views balances", c4.WithTechnology("HTTPS")). + BiRel("web", "accounts", "Reads from and writes to", c4.WithTechnology("SQL/TCP")). + Rel("web", "mail", "Sends e-mail using", c4.WithTechnology("SMTP")). + String() + + err = markdown.NewMarkdown(f). + H2("C4 Context"). + CodeBlocks(markdown.SyntaxHighlightMermaid, diagram). + Build() + + if err != nil { + panic(err) + } +} +``` + +A boundary is a pair of calls rather than a nested builder: `Boundary`, `EnterpriseBoundary` and `SystemBoundary` open one, everything after belongs to it, and `BoundaryEnd` closes it. Leaving one open is reported from `Build`, because mermaid refuses a diagram whose brace never closes. + +Labels are escaped with the entity form mermaid decodes, so a quotation mark or a `#` in one cannot break the macro syntax. The title is the exception: mermaid reads the rest of the line, quotes and all, so the package does not quote it. + +Plain text output: [markdown is here](./doc/c4/generated.md) +```` +## C4 Context +```mermaid +C4Context + title System Context: Internet Banking + Enterprise_Boundary(bank, "Big Bank plc") { + Person(customer, "Personal Banking Customer", "A customer of the bank.") + System_Boundary(banking, "Internet Banking") { + System(web, "Internet Banking System", "Shows account information.") + SystemDb(accounts, "Accounts Database") + } + } + System_Ext(mail, "E-mail System", "The internal Microsoft Exchange system.") + Rel(customer, web, "Views balances", "HTTPS") + BiRel(web, accounts, "Reads from and writes to", "SQL/TCP") + Rel(web, mail, "Sends e-mail using", "SMTP") +``` +```` + +Mermaid output: +```mermaid +C4Context + title System Context: Internet Banking + Enterprise_Boundary(bank, "Big Bank plc") { + Person(customer, "Personal Banking Customer", "A customer of the bank.") + System_Boundary(banking, "Internet Banking") { + System(web, "Internet Banking System", "Shows account information.") + SystemDb(accounts, "Accounts Database") + } + } + System_Ext(mail, "E-mail System", "The internal Microsoft Exchange system.") + Rel(customer, web, "Views balances", "HTTPS") + BiRel(web, accounts, "Reads from and writes to", "SQL/TCP") + Rel(web, mail, "Sends e-mail using", "SMTP") +``` + ## Creating an index for a directory full of markdown files The markdown package can create an index for Markdown files within the specified directory. This feature was added to generate indexes for Markdown documents produced by [nao1215/spectest](https://github.com/nao1215/spectest). diff --git a/SPEC.md b/SPEC.md index bcb906a..8141ecb 100644 --- a/SPEC.md +++ b/SPEC.md @@ -18,7 +18,7 @@ Two helpers fall outside GFM and are documented here so their behavior is not mi - `Highlight` emits `==text==`. GitHub does not render this; Obsidian, Bear, and several static site generators do. It is kept because it has always been part of the API and it costs nothing, but it is not part of the GFM target. - The badge helpers (`RedBadge` and friends) emit an image link pointing at `img.shields.io`. The markdown is plain GFM; what the image looks like is up to that external service. -Mermaid diagram bodies follow [the mermaid syntax](https://mermaid.js.org/intro/syntax-reference.html) rather than GFM, since a markdown parser treats them as opaque code block content. Diagram titles are emitted as a YAML front matter block inside the diagram, which is how mermaid itself expects them. +Mermaid diagram bodies follow [the mermaid syntax](https://mermaid.js.org/intro/syntax-reference.html) rather than GFM, since a markdown parser treats them as opaque code block content. Diagram titles are emitted as a YAML front matter block inside the diagram, which is how mermaid itself expects them; the exception is the C4 diagram, which draws a `title` statement and ignores the front matter. ## Out of scope diff --git a/contract_test.go b/contract_test.go index 8f71d8b..6ab8b2f 100644 --- a/contract_test.go +++ b/contract_test.go @@ -15,6 +15,7 @@ import ( "github.com/nao1215/markdown/internal/golden" "github.com/nao1215/markdown/mermaid/arch" "github.com/nao1215/markdown/mermaid/block" + "github.com/nao1215/markdown/mermaid/c4" "github.com/nao1215/markdown/mermaid/class" "github.com/nao1215/markdown/mermaid/er" "github.com/nao1215/markdown/mermaid/flowchart" @@ -1380,6 +1381,16 @@ func mermaidBuilders() []mermaidBuilder { String() }, }, + { + name: "c4", + build: func() string { + return c4.NewDiagram(io.Discard). + Person("customer", "Customer"). + System("ledger", "Ledger"). + Rel("customer", "ledger", "Uses"). + String() + }, + }, { name: "class", build: func() string { diff --git a/doc/c4/generated.md b/doc/c4/generated.md new file mode 100644 index 0000000..bde5ffe --- /dev/null +++ b/doc/c4/generated.md @@ -0,0 +1,17 @@ +## C4 Context + +```mermaid +C4Context + title System Context: Internet Banking + Enterprise_Boundary(bank, "Big Bank plc") { + Person(customer, "Personal Banking Customer", "A customer of the bank.") + System_Boundary(banking, "Internet Banking") { + System(web, "Internet Banking System", "Shows account information.") + SystemDb(accounts, "Accounts Database") + } + } + System_Ext(mail, "E-mail System", "The internal Microsoft Exchange system.") + Rel(customer, web, "Views balances", "HTTPS") + BiRel(web, accounts, "Reads from and writes to", "SQL/TCP") + Rel(web, mail, "Sends e-mail using", "SMTP") +``` diff --git a/doc/c4/main.go b/doc/c4/main.go new file mode 100644 index 0000000..7d3e745 --- /dev/null +++ b/doc/c4/main.go @@ -0,0 +1,50 @@ +//go:build linux || darwin + +// Package main is generating mermaid C4 context diagram. +package main + +import ( + "io" + "os" + + "github.com/nao1215/markdown" + "github.com/nao1215/markdown/mermaid/c4" +) + +// This file is gated by //go:build linux || darwin, so //go:generate is skipped +// on Windows. To regenerate generated.md on Windows, run under WSL or via CI. +//go:generate go run main.go + +func main() { + f, err := os.Create("generated.md") + if err != nil { + panic(err) + } + defer func() { + if err := f.Close(); err != nil { + panic(err) + } + }() + + diagram := c4.NewDiagram(io.Discard, c4.WithTitle("System Context: Internet Banking")). + EnterpriseBoundary("bank", "Big Bank plc"). + Person("customer", "Personal Banking Customer", c4.WithDescription("A customer of the bank.")). + SystemBoundary("banking", "Internet Banking"). + System("web", "Internet Banking System", c4.WithDescription("Shows account information.")). + SystemDb("accounts", "Accounts Database"). + BoundaryEnd(). + BoundaryEnd(). + SystemExt("mail", "E-mail System", c4.WithDescription("The internal Microsoft Exchange system.")). + Rel("customer", "web", "Views balances", c4.WithTechnology("HTTPS")). + BiRel("web", "accounts", "Reads from and writes to", c4.WithTechnology("SQL/TCP")). + Rel("web", "mail", "Sends e-mail using", c4.WithTechnology("SMTP")). + String() + + err = markdown.NewMarkdown(f, markdown.WithBlockSpacing()). + H2("C4 Context"). + CodeBlocks(markdown.SyntaxHighlightMermaid, diagram). + Build() + if err != nil { + panic(err) + } +} diff --git a/doc/edgecase/c4.md b/doc/edgecase/c4.md new file mode 100644 index 0000000..464bb3d --- /dev/null +++ b/doc/edgecase/c4.md @@ -0,0 +1,22 @@ +# C4 context rendering edge cases + +Every label below holds the punctuation this diagram type can carry. Generated by doc/edgecase/main.go and rendered in continuous integration, so a quoting defect fails the build rather than reaching a diagram. + +```mermaid +C4Context + title title "'#35;#59;[](){}🎉日本語:,*-|%%\ + Enterprise_Boundary(enterprise, "x#quot;'#35;;[](){}
🎉日本語:,*-|%%\x") { + Person(person, "x#quot;'#35;;[](){}
🎉日本語:,*-|%%\x", "before #quot;'#35;;[](){}
🎉日本語:,*-|%%\ after") + System_Boundary(systems, "x#quot;'#35;;[](){}
🎉日本語:,*-|%%\x nested") { + System(system, "x#quot;'#35;;[](){}
🎉日本語:,*-|%%\x", "before #quot;'#35;;[](){}
🎉日本語:,*-|%%\ after") + } + } + Boundary(outside, "x#quot;'#35;;[](){}
🎉日本語:,*-|%%\x", "x#quot;'#35;;[](){}
🎉日本語:,*-|%%\x") { + System_Ext(external, "x#quot;'#35;;[](){}
🎉日本語:,*-|%%\x") + } + Person_Ext(auditor, "x#quot;'#35;;[](){}
🎉日本語:,*-|%%\x") + SystemDb(db, "x#quot;'#35;;[](){}
🎉日本語:,*-|%%\x") + SystemQueue(queue, "x#quot;'#35;;[](){}
🎉日本語:,*-|%%\x") + Rel(person, system, "before #quot;'#35;;[](){}
🎉日本語:,*-|%%\ after", "x#quot;'#35;;[](){}
🎉日本語:,*-|%%\x") + BiRel(system, db, "before #quot;'#35;;[](){}
🎉日本語:,*-|%%\ after") +``` diff --git a/doc/edgecase/main.go b/doc/edgecase/main.go index 23cc607..9cf6715 100644 --- a/doc/edgecase/main.go +++ b/doc/edgecase/main.go @@ -23,6 +23,7 @@ import ( "github.com/nao1215/markdown" "github.com/nao1215/markdown/mermaid/arch" "github.com/nao1215/markdown/mermaid/block" + "github.com/nao1215/markdown/mermaid/c4" "github.com/nao1215/markdown/mermaid/class" "github.com/nao1215/markdown/mermaid/er" "github.com/nao1215/markdown/mermaid/flowchart" @@ -70,6 +71,11 @@ func supported(diagram string) string { // plain emoji and Japanese text. "architecture": "", "block": `"'#;[](){}
` + emoji + japanese + `:,*-|%%`, + // c4 escapes a quote and a "#" in a label as the entity form mermaid + // decodes, and a "#" and a ";" in the unquoted title the same way, so + // every character below survives both. Only a line break is left out: + // one macro is one line, and "
" is how a label breaks one. + "c4": `"'#;[](){}
` + emoji + japanese + `:,*-|%%\`, // class: ";" and ":" end a relation label. "class": `"'#[](){}` + emoji + japanese + `,*-|%%`, // er: a double quote ends the comment it is written in. @@ -212,6 +218,7 @@ func diagrams() []diagram { return []diagram{ {name: "Architecture", file: "architecture", build: architecture}, {name: "Block", file: "block", build: blockDiagram}, + {name: "C4 context", file: "c4", build: c4Context}, {name: "Class", file: "class", build: classDiagram}, {name: "Entity relationship", file: "er", build: entityRelationship}, {name: "Flowchart", file: "flowchart", build: flowchartDiagram}, @@ -256,6 +263,26 @@ func blockDiagram(diagram string) string { String() } +// c4Context is the C4 context diagram's edge case document. +func c4Context(diagram string) string { + return c4.NewDiagram(io.Discard, c4.WithTitle(title(diagram))). + EnterpriseBoundary("enterprise", shortLabel(diagram)). + Person("person", shortLabel(diagram), c4.WithDescription(label(diagram))). + SystemBoundary("systems", shortLabel(diagram)+" nested"). + System("system", shortLabel(diagram), c4.WithDescription(label(diagram))). + BoundaryEnd(). + BoundaryEnd(). + Boundary("outside", shortLabel(diagram), c4.WithBoundaryType(shortLabel(diagram))). + SystemExt("external", shortLabel(diagram)). + BoundaryEnd(). + PersonExt("auditor", shortLabel(diagram)). + SystemDb("db", shortLabel(diagram)). + SystemQueue("queue", shortLabel(diagram)). + Rel("person", "system", label(diagram), c4.WithTechnology(shortLabel(diagram))). + BiRel("system", "db", label(diagram)). + String() +} + func classDiagram(diagram string) string { return class.NewDiagram(io.Discard, class.WithTitle(title(diagram))). Class("Account", class.WithPublicField("string", "id")). diff --git a/mermaid/c4/c4.go b/mermaid/c4/c4.go new file mode 100644 index 0000000..9a29dcb --- /dev/null +++ b/mermaid/c4/c4.go @@ -0,0 +1,458 @@ +// Package c4 is mermaid C4 context diagram builder. +// +// Ref. https://mermaid.js.org/syntax/c4.html +// +// A C4 context diagram is the top level of the C4 model: the people and the +// software systems around the system being described, and the relationships +// between them. This package builds the C4Context form of it, and keeps the +// flat, chainable API the rest of the library has: an element is one call, +// a relationship is one call, and a boundary is a pair of calls that the +// elements between them belong to, the same way mermaid/treemap walks its own +// nesting. +// +// mermaid marks its C4 support experimental and says the syntax may change. +// The scope here is deliberately narrow because of that: C4Context with its +// elements, boundaries and relationships. C4Container, C4Component, C4Dynamic, +// C4Deployment and the UpdateElementStyle family are left out, and each can +// arrive later as a new method without changing anything that exists. +// +// Errors are recorded rather than returned from every call: the chain runs to +// the end and the error surfaces from Build. A nil writer and a writer that +// refuses the diagram are both reported rather than causing a panic, and +// String returns the diagram without needing a writer at all. +package c4 + +import ( + "errors" + "fmt" + "io" + "strings" + + "github.com/nao1215/markdown/internal" +) + +const ( + // c4LinesCap is the number of lines a small diagram starts with. + c4LinesCap int = 8 + // header is the keyword the diagram starts with. + header = "C4Context" + // indentUnit is one level of boundary nesting. + indentUnit = " " +) + +// Diagram is a C4 context diagram builder. +type Diagram struct { + // body is the C4 context diagram body. + body []string + // dest is the output destination for the C4 context diagram body. + dest io.Writer + // err manages errors that occur in all parts of the diagram building. + err error + // depth is how many boundaries are open, counted in indentUnits. + depth int +} + +// NewDiagram returns a new Diagram. +func NewDiagram(w io.Writer, opts ...Option) *Diagram { + c := newConfig() + for _, opt := range opts { + opt(c) + } + + lines := make([]string, 0, c4LinesCap) + lines = append(lines, header) + + d := &Diagram{ + body: lines, + dest: w, + } + + trimmedTitle := strings.TrimSpace(c.title) + if trimmedTitle == noTitle { + return d + } + if containsNewline(trimmedTitle) { + // mermaid reads the rest of the line as the title, so a second line + // would be read as a statement of its own. + d.err = errors.New("title must not contain newline characters") + return d + } + d.body = append(d.body, indentUnit+"title "+escapeStatement(trimmedTitle)) + return d +} + +// String returns the C4 context diagram body. +func (d *Diagram) String() string { + return strings.Join(d.body, internal.LineFeed()) +} + +// Error returns the error that occurred during the C4 context diagram building. +func (d *Diagram) Error() error { + return d.err +} + +// Build writes the C4 context diagram body to the output destination. +// +// A boundary left open is reported here rather than written out: mermaid +// refuses a diagram whose brace never closes, which loses the whole drawing. +func (d *Diagram) Build() error { + if d.err != nil { + return d.err + } + if d.depth != 0 { + d.err = fmt.Errorf("%d boundary must be closed with BoundaryEnd before Build", d.depth) + return d.err + } + if d.dest == nil { + d.err = errors.New("output writer must not be nil") + return d.err + } + + if _, err := fmt.Fprint(d.dest, d.String()); err != nil { + d.err = fmt.Errorf("failed to write: %w", err) + return d.err + } + return nil +} + +// LF adds a line feed to the C4 context diagram body. +func (d *Diagram) LF() *Diagram { + if d.err != nil { + return d + } + d.body = append(d.body, "") + return d +} + +// Person adds a person inside the enterprise being described. +func (d *Diagram) Person(id, label string, opts ...ElementOption) *Diagram { + return d.element("Person", id, label, opts) +} + +// PersonExt adds a person outside the enterprise being described. mermaid +// spells the macro Person_Ext and draws it in a colder colour than Person. +func (d *Diagram) PersonExt(id, label string, opts ...ElementOption) *Diagram { + return d.element("Person_Ext", id, label, opts) +} + +// System adds a software system inside the enterprise being described. +func (d *Diagram) System(id, label string, opts ...ElementOption) *Diagram { + return d.element("System", id, label, opts) +} + +// SystemExt adds a software system outside the enterprise being described. +// mermaid spells the macro System_Ext. +func (d *Diagram) SystemExt(id, label string, opts ...ElementOption) *Diagram { + return d.element("System_Ext", id, label, opts) +} + +// SystemDb adds a software system drawn as a database. +func (d *Diagram) SystemDb(id, label string, opts ...ElementOption) *Diagram { + return d.element("SystemDb", id, label, opts) +} + +// SystemQueue adds a software system drawn as a queue. +func (d *Diagram) SystemQueue(id, label string, opts ...ElementOption) *Diagram { + return d.element("SystemQueue", id, label, opts) +} + +// Boundary opens a boundary. Everything added until the matching BoundaryEnd is +// drawn inside it. +// +// Boundaries nest, and the pair is explicit rather than a callback taking a +// nested builder: the chain stays flat, which is how every other builder in +// this library reads, and how mermaid/treemap walks its own nesting with +// Section and Parent. +func (d *Diagram) Boundary(id, label string, opts ...BoundaryOption) *Diagram { + if d.err != nil { + return d + } + + c := newBoundaryConfig() + for _, opt := range opts { + opt(c) + } + + args, err := d.boundaryArgs(id, label, strings.TrimSpace(c.boundaryType)) + if err != nil { + d.setError(err) + return d + } + return d.openBoundary("Boundary", args) +} + +// EnterpriseBoundary opens a boundary drawn as the enterprise. mermaid spells +// the macro Enterprise_Boundary. +func (d *Diagram) EnterpriseBoundary(id, label string) *Diagram { + if d.err != nil { + return d + } + + args, err := d.boundaryArgs(id, label, "") + if err != nil { + d.setError(err) + return d + } + return d.openBoundary("Enterprise_Boundary", args) +} + +// SystemBoundary opens a boundary drawn as a software system. mermaid spells +// the macro System_Boundary. +func (d *Diagram) SystemBoundary(id, label string) *Diagram { + if d.err != nil { + return d + } + + args, err := d.boundaryArgs(id, label, "") + if err != nil { + d.setError(err) + return d + } + return d.openBoundary("System_Boundary", args) +} + +// BoundaryEnd closes the boundary opened last. +// +// Calling it outside a boundary is an error rather than a silent no-op: a chain +// that has closed more boundaries than it opened is not the diagram its author +// meant. +func (d *Diagram) BoundaryEnd() *Diagram { + if d.err != nil { + return d + } + if d.depth == 0 { + d.setError(errors.New("BoundaryEnd was called outside a boundary; there is nothing to close")) + return d + } + + d.depth-- + d.body = append(d.body, d.indent()+"}") + return d +} + +// Rel adds a one way relationship from one element to another. +func (d *Diagram) Rel(from, to, label string, opts ...RelationOption) *Diagram { + return d.relation("Rel", from, to, label, opts) +} + +// BiRel adds a relationship drawn with an arrowhead at each end. +func (d *Diagram) BiRel(from, to, label string, opts ...RelationOption) *Diagram { + return d.relation("BiRel", from, to, label, opts) +} + +// element writes one element macro. +func (d *Diagram) element(macro, id, label string, opts []ElementOption) *Diagram { + if d.err != nil { + return d + } + + c := newElementConfig() + for _, opt := range opts { + opt(c) + } + + validID, err := validateIdentifier(macro+" id", id) + if err != nil { + d.setError(err) + return d + } + text, err := validateText(macro+" label", label) + if err != nil { + d.setError(err) + return d + } + + args := []string{validID, quote(text)} + description := strings.TrimSpace(c.description) + if description != "" { + if containsNewline(description) { + d.setError(fmt.Errorf("description of %s %q must not contain newline characters", macro, text)) + return d + } + args = append(args, quote(description)) + } + + d.body = append(d.body, fmt.Sprintf("%s%s(%s)", d.indent(), macro, strings.Join(args, ", "))) + return d +} + +// relation writes one relationship macro. +func (d *Diagram) relation(macro, from, to, label string, opts []RelationOption) *Diagram { + if d.err != nil { + return d + } + + c := newRelationConfig() + for _, opt := range opts { + opt(c) + } + + validFrom, err := validateIdentifier(macro+" source", from) + if err != nil { + d.setError(err) + return d + } + validTo, err := validateIdentifier(macro+" destination", to) + if err != nil { + d.setError(err) + return d + } + text, err := validateText(macro+" label", label) + if err != nil { + d.setError(err) + return d + } + + args := []string{validFrom, validTo, quote(text)} + technology := strings.TrimSpace(c.technology) + if technology != "" { + if containsNewline(technology) { + d.setError(fmt.Errorf("technology of %s %q must not contain newline characters", macro, text)) + return d + } + args = append(args, quote(technology)) + } + + d.body = append(d.body, fmt.Sprintf("%s%s(%s)", d.indent(), macro, strings.Join(args, ", "))) + return d +} + +// boundaryArgs validates a boundary's parts and returns them ready to be +// written between the macro's parentheses. +func (d *Diagram) boundaryArgs(id, label, boundaryType string) ([]string, error) { + validID, err := validateIdentifier("boundary id", id) + if err != nil { + return nil, err + } + text, err := validateText("boundary label", label) + if err != nil { + return nil, err + } + + args := []string{validID, quote(text)} + if boundaryType != "" { + if containsNewline(boundaryType) { + return nil, fmt.Errorf("type of boundary %q must not contain newline characters", text) + } + args = append(args, quote(boundaryType)) + } + return args, nil +} + +// openBoundary writes the opening line of a boundary and descends into it. +func (d *Diagram) openBoundary(macro string, args []string) *Diagram { + d.body = append(d.body, fmt.Sprintf("%s%s(%s) {", d.indent(), macro, strings.Join(args, ", "))) + d.depth++ + return d +} + +// indent returns the prefix of a line at the current nesting. +func (d *Diagram) indent() string { + return indentUnit + strings.Repeat(indentUnit, d.depth) +} + +// setError records the first error and leaves any later one alone, because the +// first is the one that explains the rest. +func (d *Diagram) setError(err error) { + if d.err == nil { + d.err = err + } +} + +// validateText returns value ready to be quoted into a macro argument. +func validateText(fieldName, value string) (string, error) { + trimmed := strings.TrimSpace(value) + if trimmed == "" { + return "", fmt.Errorf("%s must not be empty", fieldName) + } + if containsNewline(trimmed) { + // One macro is one line, so a label spanning lines would be read as a + // statement of its own. "
" is how a C4 label breaks a line. + return "", fmt.Errorf("%s must not contain newline characters", fieldName) + } + return trimmed, nil +} + +// validateIdentifier returns value ready to be written as a macro's bare +// identifier. +// +// An identifier names an element for the relationships that point at it and is +// never drawn, so nothing is escaped here: what a caller passes is what the +// other macros have to spell. A comma ends the argument it is written in, and +// the remaining characters below are the macro's own punctuation. mermaid +// happens to accept some of them today, because its lexer stops at the first +// comma, but an identifier that only works by accident is worth rejecting while +// this package is new. +func validateIdentifier(fieldName, value string) (string, error) { + trimmed := strings.TrimSpace(value) + if trimmed == "" { + return "", fmt.Errorf("%s must not be empty", fieldName) + } + if containsNewline(trimmed) { + return "", fmt.Errorf("%s must not contain newline characters", fieldName) + } + if i := strings.IndexAny(trimmed, `,()"{}`); i >= 0 { + return "", fmt.Errorf("%s must not contain %q, which is C4 macro syntax", fieldName, trimmed[i:i+1]) + } + return trimmed, nil +} + +// quote returns value as a quoted macro argument. +// +// A double quote ends the argument, and neither of the two escapes that look +// obvious works: a backslash makes mermaid refuse the diagram, and doubling the +// quote silently splits the argument in two, so Rel(a, b, "x""y") draws "y" as +// the technology rather than as part of the label. What mermaid does implement +// is its own entity form, "#quot;", which was found by rendering all three. +// +// A "#" is escaped first and for the same reason: mermaid reads "#word;" and +// "#123;" as entities, so a label holding "#quot;" or "#39;" would otherwise +// come back as a character the caller never wrote. Both replacements happen in +// one pass, because a second pass over the first one's output would escape the +// "#" it just wrote. +func quote(value string) string { + var b strings.Builder + b.Grow(len(value) + 2) //nolint:mnd // the two quotes around the value. + b.WriteByte('"') + for _, r := range value { + switch r { + case '#': + b.WriteString("#35;") + case '"': + b.WriteString("#quot;") + default: + b.WriteRune(r) + } + } + b.WriteByte('"') + return b.String() +} + +// escapeStatement returns value ready to be written as the rest of a statement +// line. +// +// The title is the one place a C4 diagram takes unquoted text, so the argument +// escaping above does not apply: a "#quot;" would be read as an entity but a +// plain quotation mark is drawn as itself. What the unquoted lexer refuses is +// "#", which starts a comment, and ";", which ends the statement; both are +// written as the entity form mermaid decodes back into them. +func escapeStatement(value string) string { + var b strings.Builder + b.Grow(len(value)) + for _, r := range value { + switch r { + case '#': + b.WriteString("#35;") + case ';': + b.WriteString("#59;") + default: + b.WriteRune(r) + } + } + return b.String() +} + +// containsNewline reports whether value holds a line ending of either kind. +func containsNewline(value string) bool { + return strings.ContainsAny(value, "\n\r") +} diff --git a/mermaid/c4/c4_test.go b/mermaid/c4/c4_test.go new file mode 100644 index 0000000..0ed01fc --- /dev/null +++ b/mermaid/c4/c4_test.go @@ -0,0 +1,464 @@ +package c4_test + +import ( + "bytes" + "errors" + "io" + "strings" + "testing" + + "github.com/nao1215/markdown/internal" + "github.com/nao1215/markdown/internal/buildertest" + "github.com/nao1215/markdown/internal/golden" + "github.com/nao1215/markdown/mermaid/c4" +) + +// errWrite is the failure the writer below reports, so the test can assert that +// Build passed it through rather than inventing an error of its own. +var errWrite = errors.New("write failed") + +// errWriter fails every write, which is what a full disk or a closed pipe looks +// like to Build. +type errWriter struct{} + +func (errWriter) Write([]byte) (int, error) { + return 0, errWrite +} + +// lines joins the given lines with the line ending the library writes on this +// platform, which is what String returns them joined with. +func lines(want ...string) string { + return strings.Join(want, internal.LineFeed()) +} + +func TestDiagram(t *testing.T) { + t.Parallel() + + tests := map[string]struct { + build func(io.Writer) *c4.Diagram + want string + }{ + "an empty diagram is the header alone": { + build: func(w io.Writer) *c4.Diagram { + return c4.NewDiagram(w) + }, + want: "C4Context", + }, + "a title is a statement rather than front matter": { + build: func(w io.Writer) *c4.Diagram { + return c4.NewDiagram(w, c4.WithTitle("Banking Context")) + }, + want: lines("C4Context", " title Banking Context"), + }, + "a title keeps the quotation marks a caller wrote": { + // The C4 title is the rest of the line, quotes included, so this + // package must not add its own: they would be drawn. + build: func(w io.Writer) *c4.Diagram { + return c4.NewDiagram(w, c4.WithTitle(`The "Core" Ledger`)) + }, + want: lines("C4Context", ` title The "Core" Ledger`), + }, + "a title escapes the punctuation its lexer has taken": { + build: func(w io.Writer) *c4.Diagram { + return c4.NewDiagram(w, c4.WithTitle("Ledger #1; v2")) + }, + want: lines("C4Context", " title Ledger #35;1#59; v2"), + }, + "a title is trimmed and a blank one writes no statement": { + build: func(w io.Writer) *c4.Diagram { + return c4.NewDiagram(w, c4.WithTitle(" ")) + }, + want: "C4Context", + }, + "every element kind writes its own macro": { + build: func(w io.Writer) *c4.Diagram { + return c4.NewDiagram(w). + Person("p", "Customer"). + PersonExt("pe", "Auditor"). + System("s", "Ledger"). + SystemExt("se", "Mail"). + SystemDb("db", "Accounts"). + SystemQueue("q", "Events") + }, + want: lines( + "C4Context", + ` Person(p, "Customer")`, + ` Person_Ext(pe, "Auditor")`, + ` System(s, "Ledger")`, + ` System_Ext(se, "Mail")`, + ` SystemDb(db, "Accounts")`, + ` SystemQueue(q, "Events")`, + ), + }, + "a description is a third argument, and an empty one is left out": { + build: func(w io.Writer) *c4.Diagram { + return c4.NewDiagram(w). + Person("p", "Customer", c4.WithDescription("Holds an account.")). + System("s", "Ledger", c4.WithDescription(" ")) + }, + want: lines( + "C4Context", + ` Person(p, "Customer", "Holds an account.")`, + ` System(s, "Ledger")`, + ), + }, + "a relationship carries an optional technology": { + build: func(w io.Writer) *c4.Diagram { + return c4.NewDiagram(w). + Rel("p", "s", "Views balances"). + Rel("p", "s", "Pays", c4.WithTechnology("HTTPS")). + BiRel("s", "db", "Syncs"). + BiRel("s", "db", "Streams", c4.WithTechnology("gRPC")) + }, + want: lines( + "C4Context", + ` Rel(p, s, "Views balances")`, + ` Rel(p, s, "Pays", "HTTPS")`, + ` BiRel(s, db, "Syncs")`, + ` BiRel(s, db, "Streams", "gRPC")`, + ), + }, + "boundaries nest and indent what they hold": { + build: func(w io.Writer) *c4.Diagram { + return c4.NewDiagram(w). + EnterpriseBoundary("e", "Big Bank"). + Person("p", "Customer"). + SystemBoundary("b", "Internet Banking"). + System("s", "Ledger"). + BoundaryEnd(). + BoundaryEnd(). + Boundary("r", "Regulator", c4.WithBoundaryType("external")). + SystemExt("reg", "Reporting"). + BoundaryEnd(). + Rel("p", "s", "Uses") + }, + want: lines( + "C4Context", + ` Enterprise_Boundary(e, "Big Bank") {`, + ` Person(p, "Customer")`, + ` System_Boundary(b, "Internet Banking") {`, + ` System(s, "Ledger")`, + ` }`, + ` }`, + ` Boundary(r, "Regulator", "external") {`, + ` System_Ext(reg, "Reporting")`, + ` }`, + ` Rel(p, s, "Uses")`, + ), + }, + "a boundary type is trimmed away when it is blank": { + build: func(w io.Writer) *c4.Diagram { + return c4.NewDiagram(w). + Boundary("r", "Regulator", c4.WithBoundaryType(" ")). + BoundaryEnd() + }, + want: lines("C4Context", ` Boundary(r, "Regulator") {`, " }"), + }, + "a quotation mark in an argument becomes the entity mermaid decodes": { + // Neither a backslash nor a doubled quote works here: the first + // makes mermaid refuse the diagram and the second silently splits + // the argument in two. See the quote doc comment. + build: func(w io.Writer) *c4.Diagram { + return c4.NewDiagram(w).Person("p", `The "Core" Team`) + }, + want: lines("C4Context", ` Person(p, "The #quot;Core#quot; Team")`), + }, + "a hash in an argument is escaped so it cannot start an entity": { + build: func(w io.Writer) *c4.Diagram { + return c4.NewDiagram(w).Person("p", "Ticket #quot; and #39;") + }, + want: lines("C4Context", ` Person(p, "Ticket #35;quot; and #35;39;")`), + }, + "the punctuation a C4 label may carry is left alone": { + build: func(w io.Writer) *c4.Diagram { + return c4.NewDiagram(w).Person("p", `x'#;[](){}
🎉日本語:,*-|%%\x`) + }, + want: lines("C4Context", ` Person(p, "x'#35;;[](){}
🎉日本語:,*-|%%\x")`), + }, + "text is trimmed": { + build: func(w io.Writer) *c4.Diagram { + return c4.NewDiagram(w). + Person(" p ", " Customer ", c4.WithDescription(" Holds an account. ")). + Rel(" p ", " s ", " Uses ", c4.WithTechnology(" HTTPS ")) + }, + want: lines( + "C4Context", + ` Person(p, "Customer", "Holds an account.")`, + ` Rel(p, s, "Uses", "HTTPS")`, + ), + }, + "LF adds a blank line": { + build: func(w io.Writer) *c4.Diagram { + return c4.NewDiagram(w).Person("p", "Customer").LF().System("s", "Ledger") + }, + want: lines("C4Context", ` Person(p, "Customer")`, "", ` System(s, "Ledger")`), + }, + } + + for name, tt := range tests { + t.Run(name, func(t *testing.T) { + t.Parallel() + + buf := &bytes.Buffer{} + d := tt.build(buf) + if err := d.Build(); err != nil { + t.Fatalf("Build() = %v, want nil", err) + } + if got := buf.String(); got != tt.want { + t.Errorf("Build() wrote\n%q\nwant\n%q", got, tt.want) + } + if got := d.String(); got != tt.want { + t.Errorf("String() = \n%q\nwant\n%q", got, tt.want) + } + }) + } +} + +func TestDiagramRecordsBadInput(t *testing.T) { + t.Parallel() + + tests := map[string]struct { + build func(io.Writer) *c4.Diagram + want string + }{ + "a title spanning lines": { + build: func(w io.Writer) *c4.Diagram { + return c4.NewDiagram(w, c4.WithTitle("Ledger\nv2")) + }, + want: "title must not contain newline characters", + }, + "an empty element id": { + build: func(w io.Writer) *c4.Diagram { + return c4.NewDiagram(w).Person(" ", "Customer") + }, + want: "Person id must not be empty", + }, + "an element id spanning lines": { + build: func(w io.Writer) *c4.Diagram { + return c4.NewDiagram(w).System("a\nb", "Ledger") + }, + want: "System id must not contain newline characters", + }, + "an element id holding macro syntax": { + build: func(w io.Writer) *c4.Diagram { + return c4.NewDiagram(w).SystemDb("a,b", "Accounts") + }, + want: `SystemDb id must not contain ",", which is C4 macro syntax`, + }, + "an empty element label": { + build: func(w io.Writer) *c4.Diagram { + return c4.NewDiagram(w).SystemQueue("q", " ") + }, + want: "SystemQueue label must not be empty", + }, + "an element label spanning lines": { + build: func(w io.Writer) *c4.Diagram { + return c4.NewDiagram(w).PersonExt("pe", "Audit\nor") + }, + want: "Person_Ext label must not contain newline characters", + }, + "a description spanning lines": { + build: func(w io.Writer) *c4.Diagram { + return c4.NewDiagram(w).SystemExt("se", "Mail", c4.WithDescription("a\nb")) + }, + want: `description of System_Ext "Mail" must not contain newline characters`, + }, + "an empty boundary id": { + build: func(w io.Writer) *c4.Diagram { + return c4.NewDiagram(w).Boundary("", "Regulator") + }, + want: "boundary id must not be empty", + }, + "an empty enterprise boundary label": { + build: func(w io.Writer) *c4.Diagram { + return c4.NewDiagram(w).EnterpriseBoundary("e", " ") + }, + want: "boundary label must not be empty", + }, + "a system boundary id holding macro syntax": { + build: func(w io.Writer) *c4.Diagram { + return c4.NewDiagram(w).SystemBoundary("a(b", "Internet Banking") + }, + want: `boundary id must not contain "(", which is C4 macro syntax`, + }, + "a boundary type spanning lines": { + build: func(w io.Writer) *c4.Diagram { + return c4.NewDiagram(w).Boundary("r", "Regulator", c4.WithBoundaryType("a\nb")) + }, + want: `type of boundary "Regulator" must not contain newline characters`, + }, + "closing a boundary that was never opened": { + build: func(w io.Writer) *c4.Diagram { + return c4.NewDiagram(w).BoundaryEnd() + }, + want: "BoundaryEnd was called outside a boundary", + }, + "leaving a boundary open": { + build: func(w io.Writer) *c4.Diagram { + return c4.NewDiagram(w).SystemBoundary("b", "Internet Banking").System("s", "Ledger") + }, + want: "1 boundary must be closed with BoundaryEnd before Build", + }, + "an empty relationship source": { + build: func(w io.Writer) *c4.Diagram { + return c4.NewDiagram(w).Rel("", "s", "Uses") + }, + want: "Rel source must not be empty", + }, + "a relationship destination holding macro syntax": { + build: func(w io.Writer) *c4.Diagram { + return c4.NewDiagram(w).BiRel("p", `s"x`, "Uses") + }, + want: `BiRel destination must not contain "\"", which is C4 macro syntax`, + }, + "an empty relationship label": { + build: func(w io.Writer) *c4.Diagram { + return c4.NewDiagram(w).Rel("p", "s", "") + }, + want: "Rel label must not be empty", + }, + "a technology spanning lines": { + build: func(w io.Writer) *c4.Diagram { + return c4.NewDiagram(w).Rel("p", "s", "Uses", c4.WithTechnology("a\nb")) + }, + want: `technology of Rel "Uses" must not contain newline characters`, + }, + } + + for name, tt := range tests { + t.Run(name, func(t *testing.T) { + t.Parallel() + + d := tt.build(io.Discard) + err := d.Build() + if err == nil { + t.Fatalf("Build() = nil, want an error mentioning %q", tt.want) + } + if !strings.Contains(err.Error(), tt.want) { + t.Errorf("Build() = %v, want it to mention %q", err, tt.want) + } + if d.Error() == nil { + t.Error("Error() = nil after a failed Build()") + } + }) + } +} + +// TestTheFirstErrorIsKept covers the rule the whole library shares: the chain +// runs to the end after a bad call, and the error that surfaces is the first +// one, because that is the one that explains the rest. +func TestTheFirstErrorIsKept(t *testing.T) { + t.Parallel() + + d := c4.NewDiagram(io.Discard). + Person("", "Customer"). + System("s,x", "Ledger"). + BoundaryEnd() + + err := d.Build() + if err == nil { + t.Fatal("Build() = nil, want the first error") + } + if want := "Person id must not be empty"; !strings.Contains(err.Error(), want) { + t.Errorf("Build() = %v, want the first error %q", err, want) + } +} + +// TestBuildWithNilWriter covers the case where a diagram is built for String() +// only and Build() is called by mistake. Build() must return an error rather +// than dereferencing the nil writer. +func TestBuildWithNilWriter(t *testing.T) { + t.Parallel() + + defer func() { + if r := recover(); r != nil { + t.Fatalf("Build() panicked with a nil writer: %v", r) + } + }() + + d := c4.NewDiagram(nil).Person("p", "Customer") + + // String() has always worked without a writer, and callers rely on it. + if d.String() == "" { + t.Fatal("String() returned nothing for a diagram with a person in it") + } + + err := d.Build() + if err == nil { + t.Fatal("Build() with a nil writer must return an error") + } + if err.Error() != "output writer must not be nil" { + t.Errorf("unexpected error message: %v", err) + } +} + +// TestBuildReportsWriteFailure covers the branch where the destination accepts +// the diagram and then fails. Silently returning nil there would hand the caller +// a document that was never written. +func TestBuildReportsWriteFailure(t *testing.T) { + t.Parallel() + + err := c4.NewDiagram(errWriter{}).Person("p", "Customer").Build() + if err == nil { + t.Fatal("Build must report a failing writer") + } + if !errors.Is(err, errWrite) { + t.Errorf("Build lost the destination error: %v", err) + } +} + +// TestBuildContract asserts the error handling every builder in this module +// shares. The contract itself lives in internal/buildertest. +func TestBuildContract(t *testing.T) { + t.Parallel() + + buildertest.RunBuildContract(t, func(w io.Writer) buildertest.Builder { + return c4.NewDiagram(w).Person("p", "Customer").System("s", "Ledger").Rel("p", "s", "Uses") + }) +} + +// TestRecordedErrorContract asserts that closing a boundary that was never +// opened surfaces from Build. +func TestRecordedErrorContract(t *testing.T) { + t.Parallel() + + buildertest.RunRecordedErrorContract(t, func(w io.Writer) buildertest.Builder { + return c4.NewDiagram(w).BoundaryEnd() + }) +} + +// TestGoldenC4 pins the rendered diagram of every builder method and every +// option of this package, including both escapes and three levels of nesting. +func TestGoldenC4(t *testing.T) { + t.Parallel() + + buf := &bytes.Buffer{} + err := c4.NewDiagram(buf, c4.WithTitle(`Ledger #1; the "core"`)). + EnterpriseBoundary("bank", "Big Bank plc"). + Person("customer", "Personal Banking Customer", c4.WithDescription("Holds a personal account.")). + SystemBoundary("banking", "Internet Banking"). + System("web", "Internet Banking System", c4.WithDescription(`Shows the "balance" (in full).`)). + SystemDb("accounts", "Accounts Database"). + SystemQueue("events", "Event Bus", c4.WithDescription("Carries domain events.")). + BoundaryEnd(). + BoundaryEnd(). + LF(). + PersonExt("auditor", "External Auditor"). + SystemExt("mail", "E-mail System", c4.WithDescription("Microsoft Exchange.")). + Boundary("regulator", "Regulator", c4.WithBoundaryType("external")). + SystemExt("reporting", "Regulatory Reporting"). + BoundaryEnd(). + LF(). + Rel("customer", "web", "Views balances", c4.WithTechnology("HTTPS (TLS 1.3)")). + BiRel("web", "accounts", "Reads from and writes to", c4.WithTechnology("SQL/TCP")). + Rel("web", "mail", "Sends e-mail using", c4.WithTechnology("SMTP")). + Rel("auditor", "reporting", `Reads "the report"`). + Build() + if err != nil { + t.Fatalf("Build() = %v, want nil", err) + } + + if err := golden.Assert("c4.md", buf.String()); err != nil { + t.Error(err) + } +} diff --git a/mermaid/c4/config.go b/mermaid/c4/config.go new file mode 100644 index 0000000..51da00a --- /dev/null +++ b/mermaid/c4/config.go @@ -0,0 +1,100 @@ +package c4 + +// noTitle is a constant for no title. +const noTitle string = "" + +// config is the configuration for the C4 context diagram. +type config struct { + // title is the title of the C4 context diagram. + title string +} + +// newConfig returns a new config with default values. +func newConfig() *config { + return &config{ + title: noTitle, + } +} + +// Option sets the options for the Diagram struct. +type Option func(*config) + +// WithTitle sets the title configuration. +// +// The title is written as a "title" statement rather than as front matter, +// because a C4 diagram draws the statement and ignores the front matter. It is +// also the one place in this package where the text is not quoted: mermaid +// takes the rest of the line, quotes and all, so a quoted title would draw its +// own quotation marks. +func WithTitle(title string) Option { + return func(c *config) { + c.title = title + } +} + +// elementConfig is the optional part of an element. +type elementConfig struct { + // description is the sentence drawn under an element's label. + description string +} + +func newElementConfig() *elementConfig { + return &elementConfig{} +} + +// ElementOption sets the options an element takes. +type ElementOption func(*elementConfig) + +// WithDescription sets the description drawn under an element's label. +// +// An empty description is the same as none: mermaid draws nothing for it. +func WithDescription(description string) ElementOption { + return func(c *elementConfig) { + c.description = description + } +} + +// boundaryConfig is the optional part of a boundary. +type boundaryConfig struct { + // boundaryType is the tag mermaid draws in brackets beside the label. + boundaryType string +} + +func newBoundaryConfig() *boundaryConfig { + return &boundaryConfig{} +} + +// BoundaryOption sets the options a boundary takes. +type BoundaryOption func(*boundaryConfig) + +// WithBoundaryType sets the tag mermaid draws in brackets beside a boundary +// label. EnterpriseBoundary and SystemBoundary carry their own, so this applies +// to Boundary alone. +func WithBoundaryType(boundaryType string) BoundaryOption { + return func(c *boundaryConfig) { + c.boundaryType = boundaryType + } +} + +// relationConfig is the optional part of a relationship. +type relationConfig struct { + // technology is the wording drawn in brackets on the arrow. + technology string +} + +func newRelationConfig() *relationConfig { + return &relationConfig{} +} + +// RelationOption sets the options a relationship takes. +type RelationOption func(*relationConfig) + +// WithTechnology sets the technology drawn in brackets on the arrow, which is +// where a C4 diagram says how two things talk to each other. +// +// An empty technology is the same as none: mermaid draws no brackets for it. +func WithTechnology(technology string) RelationOption { + return func(c *relationConfig) { + c.technology = technology + } +} diff --git a/mermaid/c4/examples_test.go b/mermaid/c4/examples_test.go new file mode 100644 index 0000000..cf0e852 --- /dev/null +++ b/mermaid/c4/examples_test.go @@ -0,0 +1,99 @@ +//go:build linux || darwin + +package c4_test + +import ( + "io" + "os" + + md "github.com/nao1215/markdown" + "github.com/nao1215/markdown/mermaid/c4" +) + +// ExampleDiagram skips this test on Windows. +// The newline codes in the comment section where +// the expected values are written are represented as '\n', +// causing failures when testing on Windows. +func ExampleDiagram() { + diagram := c4.NewDiagram(io.Discard, c4.WithTitle("System Context: Internet Banking")). + EnterpriseBoundary("bank", "Big Bank plc"). + Person("customer", "Personal Banking Customer", c4.WithDescription("A customer of the bank.")). + SystemBoundary("banking", "Internet Banking"). + System("web", "Internet Banking System", c4.WithDescription("Shows account information.")). + SystemDb("accounts", "Accounts Database"). + BoundaryEnd(). + BoundaryEnd(). + SystemExt("mail", "E-mail System", c4.WithDescription("The internal Microsoft Exchange system.")). + Rel("customer", "web", "Views balances", c4.WithTechnology("HTTPS")). + BiRel("web", "accounts", "Reads from and writes to", c4.WithTechnology("SQL/TCP")). + Rel("web", "mail", "Sends e-mail using", c4.WithTechnology("SMTP")). + String() + + _ = md.NewMarkdown(os.Stdout). + H2("C4 Context"). + CodeBlocks(md.SyntaxHighlightMermaid, diagram). + Build() + + // Output: + // ## C4 Context + // ```mermaid + // C4Context + // title System Context: Internet Banking + // Enterprise_Boundary(bank, "Big Bank plc") { + // Person(customer, "Personal Banking Customer", "A customer of the bank.") + // System_Boundary(banking, "Internet Banking") { + // System(web, "Internet Banking System", "Shows account information.") + // SystemDb(accounts, "Accounts Database") + // } + // } + // System_Ext(mail, "E-mail System", "The internal Microsoft Exchange system.") + // Rel(customer, web, "Views balances", "HTTPS") + // BiRel(web, accounts, "Reads from and writes to", "SQL/TCP") + // Rel(web, mail, "Sends e-mail using", "SMTP") + // ``` +} + +// ExampleDiagram_boundary shows the pair of calls a boundary is: Boundary opens +// one and BoundaryEnd closes it, and what lies between belongs to it. They nest, +// and leaving one open is reported from Build rather than written out. +func ExampleDiagram_boundary() { + diagram := c4.NewDiagram(io.Discard). + Boundary("region", "eu-west-1", c4.WithBoundaryType("region")). + System("api", "Public API"). + BoundaryEnd(). + String() + + _ = md.NewMarkdown(os.Stdout). + CodeBlocks(md.SyntaxHighlightMermaid, diagram). + Build() + + // Output: + // ```mermaid + // C4Context + // Boundary(region, "eu-west-1", "region") { + // System(api, "Public API") + // } + // ``` +} + +// ExampleDiagram_quoting shows what this package does with the punctuation C4 +// has taken for itself. A quotation mark in a label becomes "#quot;" and a "#" +// becomes "#35;", because a backslash makes mermaid refuse the diagram and a +// doubled quote silently splits the argument in two. A title is the one place +// the text is not quoted, so there a "#" and a ";" are the escaped pair. +func ExampleDiagram_quoting() { + diagram := c4.NewDiagram(io.Discard, c4.WithTitle(`Ledger #1; the "core"`)). + System("ledger", `The "Core" Ledger`, c4.WithDescription("Tracks #1 of everything.")). + String() + + _ = md.NewMarkdown(os.Stdout). + CodeBlocks(md.SyntaxHighlightMermaid, diagram). + Build() + + // Output: + // ```mermaid + // C4Context + // title Ledger #35;1#59; the "core" + // System(ledger, "The #quot;Core#quot; Ledger", "Tracks #35;1 of everything.") + // ``` +} diff --git a/mermaid/c4/testdata/golden/c4.md b/mermaid/c4/testdata/golden/c4.md new file mode 100644 index 0000000..145bb3b --- /dev/null +++ b/mermaid/c4/testdata/golden/c4.md @@ -0,0 +1,21 @@ +C4Context + title Ledger #35;1#59; the "core" + Enterprise_Boundary(bank, "Big Bank plc") { + Person(customer, "Personal Banking Customer", "Holds a personal account.") + System_Boundary(banking, "Internet Banking") { + System(web, "Internet Banking System", "Shows the #quot;balance#quot; (in full).") + SystemDb(accounts, "Accounts Database") + SystemQueue(events, "Event Bus", "Carries domain events.") + } + } + + Person_Ext(auditor, "External Auditor") + System_Ext(mail, "E-mail System", "Microsoft Exchange.") + Boundary(regulator, "Regulator", "external") { + System_Ext(reporting, "Regulatory Reporting") + } + + Rel(customer, web, "Views balances", "HTTPS (TLS 1.3)") + BiRel(web, accounts, "Reads from and writes to", "SQL/TCP") + Rel(web, mail, "Sends e-mail using", "SMTP") + Rel(auditor, reporting, "Reads #quot;the report#quot;") \ No newline at end of file diff --git a/scripts/mermaid-check/check.mjs b/scripts/mermaid-check/check.mjs index 88d81f4..293acbc 100644 --- a/scripts/mermaid-check/check.mjs +++ b/scripts/mermaid-check/check.mjs @@ -146,6 +146,29 @@ function unquote(value) { return trimmed; } +// decodeEntities resolves the "#name;" and "#123;" escapes mermaid decodes +// before it draws text. +// +// The escape is how a diagram writes a character its own grammar has taken: a +// C4 title cannot hold a "#" or a ";" literally, so they arrive as "#35;" and +// "#59;" and are drawn as themselves. The title comparison below is against the +// drawing, so it has to read the escape the same way mermaid does or it reports +// a title that is present as missing. +// +// mermaid resolves the numeric form itself, as a character code, and hands the +// named form to the browser as "&name;", so an unknown name is drawn as that +// literal text rather than as the escape it looks like. +function decodeEntities(value) { + return value.replace(/#(\w+);/g, (whole, body) => { + if (/^\+?\d+$/.test(body)) { + return String.fromCharCode(parseInt(body, 10)); + } + const el = dom.window.document.createElement("div"); + el.innerHTML = `&${body};`; + return el.textContent; + }); +} + // declaredTitle returns the title a diagram asks for: front matter first, then // the `title` statement the flat diagram types use. // @@ -176,7 +199,7 @@ function declaredTitle(source) { for (const line of rest) { const m = line.match(/^\s*title\s+(\S.*)$/); if (m) { - return { text: unquote(m[1]), frontMatter: false }; + return { text: decodeEntities(unquote(m[1])), frontMatter: false }; } } return null; diff --git a/scripts/mermaid-check/selftest.mjs b/scripts/mermaid-check/selftest.mjs index 0b45ddb..0efe4f8 100644 --- a/scripts/mermaid-check/selftest.mjs +++ b/scripts/mermaid-check/selftest.mjs @@ -36,10 +36,18 @@ const cases = [ file: "frontmatter-comment-title.mdfixture", expect: "YAML reads its value as nothing", }, + { + file: "c4-title-line-break.mdfixture", + expect: "does not appear in the rendered diagram", + }, { file: "valid.mdfixture", expect: null, }, + { + file: "c4-escaped-title.mdfixture", + expect: null, + }, ]; let failed = 0; diff --git a/scripts/mermaid-check/testdata/c4-escaped-title.mdfixture b/scripts/mermaid-check/testdata/c4-escaped-title.mdfixture new file mode 100644 index 0000000..20cccde --- /dev/null +++ b/scripts/mermaid-check/testdata/c4-escaped-title.mdfixture @@ -0,0 +1,14 @@ +# A C4 title written with the escapes mermaid decodes + +The title holds a "#", a ";" and a quotation mark. The first two are the C4 +title lexer's own punctuation and arrive as "#35;" and "#59;"; mermaid decodes +both before it draws them, so the checker has to as well or it reports this +title as missing. + +```mermaid +C4Context + title Ledger #35;1: "core"#59; v2 + Person(customer, "Customer") + System(ledger, "Ledger") + Rel(customer, ledger, "Reads #quot;the balance#quot;") +``` diff --git a/scripts/mermaid-check/testdata/c4-title-line-break.mdfixture b/scripts/mermaid-check/testdata/c4-title-line-break.mdfixture new file mode 100644 index 0000000..3bc90eb --- /dev/null +++ b/scripts/mermaid-check/testdata/c4-title-line-break.mdfixture @@ -0,0 +1,13 @@ +# A C4 title broken across lines is lost + +"
" breaks the line in a C4 title, and the drawing then no longer carries +the text that was asked for. Decoding the escapes must not stop the checker +noticing that. + +```mermaid +C4Context + title Ledger
v2 + Person(customer, "Customer") + System(ledger, "Ledger") + Rel(customer, ledger, "Reads") +``` From 39bff095214b486946dbe9c7cd381145cd1b0d89 Mon Sep 17 00:00:00 2001 From: Naohiro CHIKAMATSU Date: Wed, 12 Aug 2026 09:33:30 +0900 Subject: [PATCH 2/2] fix: decode a numeric mermaid entity as a code point mermaid rewrites "#123;" to the HTML reference "{" and lets the browser resolve it, so a character code truncates anything past U+FFFF: "#128512;" came out as U+F600 rather than as the emoji, and the render check would have called a title that is drawn missing. Decode through the DOM the way mermaid does, and put an astral escape in the fixture so the difference is what fails if it comes back. Also spell "color" the way the rest of the repository does. --- mermaid/c4/c4.go | 2 +- scripts/mermaid-check/check.mjs | 14 +++++++------- .../testdata/c4-escaped-title.mdfixture | 5 +++-- 3 files changed, 11 insertions(+), 10 deletions(-) diff --git a/mermaid/c4/c4.go b/mermaid/c4/c4.go index 9a29dcb..f7268c1 100644 --- a/mermaid/c4/c4.go +++ b/mermaid/c4/c4.go @@ -130,7 +130,7 @@ func (d *Diagram) Person(id, label string, opts ...ElementOption) *Diagram { } // PersonExt adds a person outside the enterprise being described. mermaid -// spells the macro Person_Ext and draws it in a colder colour than Person. +// spells the macro Person_Ext and draws it in a colder color than Person. func (d *Diagram) PersonExt(id, label string, opts ...ElementOption) *Diagram { return d.element("Person_Ext", id, label, opts) } diff --git a/scripts/mermaid-check/check.mjs b/scripts/mermaid-check/check.mjs index 293acbc..1ad23e6 100644 --- a/scripts/mermaid-check/check.mjs +++ b/scripts/mermaid-check/check.mjs @@ -155,16 +155,16 @@ function unquote(value) { // drawing, so it has to read the escape the same way mermaid does or it reports // a title that is present as missing. // -// mermaid resolves the numeric form itself, as a character code, and hands the -// named form to the browser as "&name;", so an unknown name is drawn as that -// literal text rather than as the escape it looks like. +// mermaid rewrites "#123;" to the HTML reference "{" and "#name;" to +// "&name;", and lets the browser resolve both, so the decoding here goes through +// a DOM for the same reason: it agrees on the astral code points that a +// character code would truncate, and it leaves an unknown name as the literal +// text mermaid leaves it as. function decodeEntities(value) { return value.replace(/#(\w+);/g, (whole, body) => { - if (/^\+?\d+$/.test(body)) { - return String.fromCharCode(parseInt(body, 10)); - } + const reference = /^\+?\d+$/.test(body) ? `&#${body};` : `&${body};`; const el = dom.window.document.createElement("div"); - el.innerHTML = `&${body};`; + el.innerHTML = reference; return el.textContent; }); } diff --git a/scripts/mermaid-check/testdata/c4-escaped-title.mdfixture b/scripts/mermaid-check/testdata/c4-escaped-title.mdfixture index 20cccde..42281c5 100644 --- a/scripts/mermaid-check/testdata/c4-escaped-title.mdfixture +++ b/scripts/mermaid-check/testdata/c4-escaped-title.mdfixture @@ -3,11 +3,12 @@ The title holds a "#", a ";" and a quotation mark. The first two are the C4 title lexer's own punctuation and arrive as "#35;" and "#59;"; mermaid decodes both before it draws them, so the checker has to as well or it reports this -title as missing. +title as missing. The emoji is the numeric form, and it is past U+FFFF on +purpose: a character code truncates it and a code point does not. ```mermaid C4Context - title Ledger #35;1: "core"#59; v2 + title Ledger #35;1: "core"#59; v2 #128512; Person(customer, "Customer") System(ledger, "Ledger") Rel(customer, ledger, "Reads #quot;the balance#quot;")