Documentation
¶
Overview ¶
Package d2vision parses D2-generated SVG diagrams and outputs structured JSON and natural language descriptions.
D2 (https://d2lang.com) is a modern diagram scripting language. This package enables programmatic analysis of D2 diagrams by extracting node and edge information from the generated SVG files.
Basic Usage ¶
diagram, err := d2vision.ParseFile("diagram.svg")
if err != nil {
log.Fatal(err)
}
// Get JSON output
json, _ := diagram.JSONIndent("", " ")
fmt.Println(string(json))
// Get natural language description
fmt.Println(diagram.Describe())
How It Works ¶
D2 encodes node and edge IDs as base64 in CSS class names within the generated SVG. For example, the class "YQ==" decodes to "a", and "(a -> b)[0]" is encoded as "KGEgLT4gYilbMF0=". By decoding these class names, d2vision reconstructs the diagram structure including:
- Node IDs and labels
- Edge connections (source → target)
- Container/hierarchy relationships
- Shape types (rectangle, circle, cylinder, etc.)
- Visual styling information
Output Formats ¶
The package supports multiple output formats:
- JSON: Structured data suitable for programmatic consumption
- Text: Human-readable natural language description
- Summary: Brief overview of diagram contents
- LLM: Optimized format for large language model consumption
Index ¶
- Variables
- func DecodeBase64ID(encoded string) (string, error)
- func EncodeBase64ID(id string) string
- func ExtractBaseName(nodeID string) string
- func ExtractParentID(nodeID string) string
- func IsEdgeID(id string) bool
- func NormalizeID(id string) string
- type ArrowType
- type Bounds
- type Diagram
- func (d *Diagram) AnalyzeLayout() *LayoutAnalysis
- func (d *Diagram) ContainerCount() int
- func (d *Diagram) ContainerNodes() []Node
- func (d *Diagram) Describe() string
- func (d *Diagram) DescribeDetailed() string
- func (d *Diagram) DescribeForGeneration() string
- func (d *Diagram) DescribeForLLM() string
- func (d *Diagram) DescribeSummary() string
- func (d *Diagram) EdgeByID(id string) *Edge
- func (d *Diagram) EdgesFrom(nodeID string) []Edge
- func (d *Diagram) EdgesTo(nodeID string) []Edge
- func (d *Diagram) JSON() ([]byte, error)
- func (d *Diagram) JSONIndent(prefix, indent string) ([]byte, error)
- func (d *Diagram) LeafNodes() []Node
- func (d *Diagram) NodeByID(id string) *Node
- func (d *Diagram) RootNodes() []Node
- type Edge
- type EdgeEndpoints
- type EdgeStyle
- type LayoutAnalysis
- type Node
- type NodeStyle
- type OutputFormat
- type Parser
- type Point
- type ShapeType
Constants ¶
This section is empty.
Variables ¶
var Version = "0.1.0"
Version is the version of the d2vision package. This is set at build time by goreleaser via ldflags.
Functions ¶
func DecodeBase64ID ¶
DecodeBase64ID decodes a base64-encoded D2 element ID.
D2 HTML-encodes special characters (like >) before base64 encoding, so we must unescape HTML entities after decoding to get the original ID.
func EncodeBase64ID ¶
EncodeBase64ID encodes a D2 element ID to base64. Note: This does NOT HTML-encode first, so it won't produce the same result as D2 for IDs containing special characters like >.
func ExtractBaseName ¶
ExtractBaseName extracts the base name from a node ID (without parent prefix).
Examples:
- "a" -> "a"
- "container.node" -> "node"
- "a.b.c" -> "c"
func ExtractParentID ¶
ExtractParentID extracts the parent container ID from a nested node ID. Returns empty string if the node has no parent (is top-level).
Examples:
- "a" -> ""
- "container.node" -> "container"
- "a.b.c" -> "a.b"
func NormalizeID ¶
NormalizeID cleans up a D2 ID by trimming whitespace.
Types ¶
type ArrowType ¶
type ArrowType string
ArrowType represents the type of arrow on an edge endpoint.
const ( ArrowNone ArrowType = "none" ArrowTriangle ArrowType = "triangle" ArrowDiamond ArrowType = "diamond" ArrowCircle ArrowType = "circle" ArrowCrowfoot ArrowType = "crowfoot" ArrowCFOne ArrowType = "cf-one" ArrowCFMany ArrowType = "cf-many" ArrowCFOneReq ArrowType = "cf-one-required" ArrowCFManyReq ArrowType = "cf-many-required" )
Arrow type constants.
type Bounds ¶
type Bounds struct {
X float64 `json:"x"`
Y float64 `json:"y"`
Width float64 `json:"width"`
Height float64 `json:"height"`
}
Bounds represents a rectangular bounding box.
func ParseViewBox ¶
ParseViewBox parses an SVG viewBox attribute string.
type Diagram ¶
type Diagram struct {
Version string `json:"version,omitempty"`
Title string `json:"title,omitempty"`
ViewBox Bounds `json:"viewBox"`
Nodes []Node `json:"nodes"`
Edges []Edge `json:"edges"`
}
Diagram represents a parsed D2 diagram.
func ParseBytes ¶
ParseBytes parses a D2 SVG from bytes and returns a Diagram.
func ParseString ¶
ParseString parses a D2 SVG from a string and returns a Diagram.
func (*Diagram) AnalyzeLayout ¶
func (d *Diagram) AnalyzeLayout() *LayoutAnalysis
AnalyzeLayout analyzes the diagram's layout characteristics.
func (*Diagram) ContainerCount ¶
func (*Diagram) ContainerNodes ¶
ContainerNodes returns nodes that have children.
func (*Diagram) DescribeDetailed ¶
DescribeDetailed generates a detailed natural language description.
func (*Diagram) DescribeForGeneration ¶
DescribeForGeneration generates output optimized for recreating the diagram.
func (*Diagram) DescribeForLLM ¶
DescribeForLLM generates a description optimized for LLM consumption.
func (*Diagram) DescribeSummary ¶
DescribeSummary generates a brief summary of the diagram.
func (*Diagram) JSONIndent ¶
JSONIndent returns the diagram as indented JSON bytes.
type Edge ¶
type Edge struct {
ID string `json:"id"`
Source string `json:"source"`
Target string `json:"target"`
Label string `json:"label,omitempty"`
SourceArrow ArrowType `json:"sourceArrow,omitempty"`
TargetArrow ArrowType `json:"targetArrow"`
Path []Point `json:"path,omitempty"`
Style EdgeStyle `json:"style,omitzero"`
}
Edge represents a connection between two nodes in a D2 diagram.
func (Edge) ConnectionDescription ¶
ConnectionDescription returns a natural language description of the connection.
func (Edge) DisplayLabel ¶
DisplayLabel returns the label for display purposes.
func (Edge) IsBidirectional ¶
IsBidirectional returns true if the edge has arrows on both ends.
type EdgeEndpoints ¶
type EdgeEndpoints struct {
Source string // Source node ID (fully qualified with container prefix)
Target string // Target node ID (fully qualified with container prefix)
Direction string // Arrow direction: "->", "<-", or "--"
Index string // Edge index, e.g., "0"
Container string // Container scope, e.g., "container" for "container.(a -> b)[0]"
}
EdgeEndpoints represents the parsed components of an edge ID.
func ParseEdgeID ¶
func ParseEdgeID(id string) (EdgeEndpoints, bool)
ParseEdgeID extracts source and target node IDs from an edge ID.
For container-scoped edges like "container.(a -> b)[0]", the source and target are returned with the container prefix: "container.a", "container.b"
type EdgeStyle ¶
type EdgeStyle struct {
Stroke string `json:"stroke,omitempty"`
StrokeWidth float64 `json:"strokeWidth,omitempty"`
StrokeDash string `json:"strokeDash,omitempty"`
Opacity float64 `json:"opacity,omitempty"`
Animated bool `json:"animated,omitempty"`
LabelFontSize float64 `json:"labelFontSize,omitempty"`
}
EdgeStyle contains visual styling properties for an edge.
type LayoutAnalysis ¶
type LayoutAnalysis struct {
// Layout type detection
LayoutType string `json:"layoutType" toon:"LayoutType"`
Direction string `json:"direction,omitempty" toon:"Direction"`
GridColumns int `json:"gridColumns,omitempty" toon:"GridColumns"`
GridRows int `json:"gridRows,omitempty" toon:"GridRows"`
HasContainers bool `json:"hasContainers" toon:"HasContainers"`
ContainerCount int `json:"containerCount" toon:"ContainerCount"`
NestingDepth int `json:"nestingDepth" toon:"NestingDepth"`
CrossContainerEdges int `json:"crossContainerEdges" toon:"CrossContainerEdges"`
// Layout insights
Insights []string `json:"insights" toon:"Insights"`
// Generation hints
GenerationHints []string `json:"generationHints" toon:"GenerationHints"`
}
LayoutAnalysis contains analysis of a diagram's layout characteristics.
type Node ¶
type Node struct {
ID string `json:"id"`
Label string `json:"label,omitempty"`
Shape ShapeType `json:"shape"`
Bounds Bounds `json:"bounds"`
Parent string `json:"parent,omitempty"`
Children []string `json:"children,omitempty"`
Style NodeStyle `json:"style,omitzero"`
}
Node represents a node (shape) in a D2 diagram.
func (Node) DisplayLabel ¶
DisplayLabel returns the label for display purposes. If no label is set, it returns the ID.
func (Node) HasChildren ¶
HasChildren returns true if the node has child nodes.
func (Node) IsContainer ¶
IsContainer returns true if the node is a container (has children).
type NodeStyle ¶
type NodeStyle struct {
Fill string `json:"fill,omitempty"`
Stroke string `json:"stroke,omitempty"`
StrokeWidth float64 `json:"strokeWidth,omitempty"`
FontSize float64 `json:"fontSize,omitempty"`
FontColor string `json:"fontColor,omitempty"`
Opacity float64 `json:"opacity,omitempty"`
}
NodeStyle contains visual styling properties for a node.
type OutputFormat ¶
type OutputFormat string
OutputFormat specifies the output format for diagram descriptions.
const ( FormatJSON OutputFormat = "json" FormatText OutputFormat = "text" FormatSummary OutputFormat = "summary" )
type Parser ¶
type Parser struct {
// IncludePaths controls whether edge path coordinates are included in output.
IncludePaths bool
// IncludeStyles controls whether style information (fill, stroke) is extracted.
IncludeStyles bool
}
Parser parses D2-generated SVG diagrams.
D2 encodes element IDs as base64 in CSS class names. For example:
- "YQ==" decodes to "a" (a node)
- "KGEgLT4gYilbMF0=" decodes to "(a -> b)[0]" (an edge)
The parser decodes these class names to reconstruct the diagram structure.
func (*Parser) ParseBytes ¶
ParseBytes parses an SVG from bytes.
type ShapeType ¶
type ShapeType string
ShapeType represents the visual shape of a node.
const ( ShapeRectangle ShapeType = "rectangle" ShapeSquare ShapeType = "square" ShapeCircle ShapeType = "circle" ShapeOval ShapeType = "oval" ShapeCylinder ShapeType = "cylinder" ShapeDiamond ShapeType = "diamond" ShapeHexagon ShapeType = "hexagon" ShapeParallelogram ShapeType = "parallelogram" ShapeCloud ShapeType = "cloud" ShapeDocument ShapeType = "document" ShapeQueue ShapeType = "queue" ShapePackage ShapeType = "package" ShapePerson ShapeType = "person" ShapeClass ShapeType = "class" ShapeCode ShapeType = "code" ShapeImage ShapeType = "image" ShapeText ShapeType = "text" ShapeUnknown ShapeType = "unknown" )
Shape type constants.
func (ShapeType) NaturalName ¶
NaturalName returns a human-readable name for the shape.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
d2vision
command
Command d2vision parses D2-generated SVG diagrams, generates D2 code, and provides tools for AI-assisted diagram creation.
|
Command d2vision parses D2-generated SVG diagrams, generates D2 code, and provides tools for AI-assisted diagram creation. |
|
Package convert provides converters for transforming Mermaid and PlantUML diagrams into D2 format via the generate.DiagramSpec intermediate representation.
|
Package convert provides converters for transforming Mermaid and PlantUML diagrams into D2 format via the generate.DiagramSpec intermediate representation. |
|
mermaid
Package mermaid provides parsing and conversion of Mermaid diagrams to D2.
|
Package mermaid provides parsing and conversion of Mermaid diagrams to D2. |
|
plantuml
Package plantuml provides parsing and conversion of PlantUML diagrams to D2.
|
Package plantuml provides parsing and conversion of PlantUML diagrams to D2. |
|
Package format provides output format abstraction for CLI commands.
|
Package format provides output format abstraction for CLI commands. |
|
Package generate provides D2 code generation from structured specifications.
|
Package generate provides D2 code generation from structured specifications. |
|
Package icons provides access to D2's icon library hosted at icons.terrastruct.com.
|
Package icons provides access to D2's icon library hosted at icons.terrastruct.com. |
|
Package render provides D2 diagram rendering using the d2 library.
|
Package render provides D2 diagram rendering using the d2 library. |
|
Package schema provides embedded JSON Schema definitions for d2vision types.
|
Package schema provides embedded JSON Schema definitions for d2vision types. |