diff --git a/.github/workflows/build-github.yml b/.github/workflows/build-github.yml
index ed26324..c9a08a8 100644
--- a/.github/workflows/build-github.yml
+++ b/.github/workflows/build-github.yml
@@ -13,6 +13,7 @@ env:
BASE_VERSION: "2.1"
PATH_SLNX: "Lite.StateMachine.slnx"
PATH_LIB: "source\\Lite.StateMachine\\Lite.StateMachine.csproj"
+ PATH_DOTGRAPH: "source\\Lite.StateMachine.DotGraph\\Lite.StateMachine.DotGraph.csproj"
PATH_ARTIFACTS: ${{github.workspace}}\artifacts
jobs:
@@ -82,9 +83,16 @@ jobs:
if ($prerelease) { Write-Host "Version suffix=$prerelease" }
# 7. Pack NuGet
- - name: 7) Pack NuGet
+ - name: 7) Pack NuGet Packages
# Optionally, "--include-symbols"
- run: dotnet pack ${{env.PATH_LIB}} --configuration Release --no-build --output ${{env.PATH_ARTIFACTS}}
+ shell: pwsh
+ run: |
+ foreach ($project in @($env:PATH_LIB, $env:PATH_DOTGRAPH)) {
+ dotnet pack $project --configuration Release --no-build --output $env:PATH_ARTIFACTS -m:1
+ if ($LASTEXITCODE -ne 0) {
+ throw "NuGet packing failed for $project"
+ }
+ }
# dotnet pack source/Lite.StateMachine/Lite.StateMachine.csproj --configuration Release --no-build --output ./artifacts
#- name: Pack NuGet
# shell: pwsh
@@ -125,13 +133,13 @@ jobs:
## steps:
## 10) Publish to NuGet.org (master branch, push events only)
- - name: 8) NuGet Push Package
+ - name: 8) NuGet Push Packages
env:
NUGET_API_URL: "https://api.nuget.org/v3/index.json"
## Optionally pass, `--skip-duplicate` if a pkg version already exists on NuGet.org
if: github.ref == 'refs/heads/master' || startsWith(github.ref, 'refs/tags/')
- run: dotnet nuget push ${{env.PATH_ARTIFACTS}}\*.nupkg -k ${{secrets.NUGET_AUTH_TOKEN}} -s ${{env.NUGET_API_URL}}
+ run: dotnet nuget push ${{env.PATH_ARTIFACTS}}\*.nupkg -k ${{secrets.NUGET_AUTH_TOKEN}} -s ${{env.NUGET_API_URL}} --skip-duplicate
#- name: Publish to NuGet.org
# if: github.ref_name == 'master' && github.event_name == 'push'
diff --git a/.github/workflows/dotgraph.yml b/.github/workflows/dotgraph.yml
new file mode 100644
index 0000000..d844031
--- /dev/null
+++ b/.github/workflows/dotgraph.yml
@@ -0,0 +1,42 @@
+name: DOT rendering on Windows, Linux, and macOS
+
+on:
+ push:
+ branches: [master, develop]
+ pull_request:
+ branches: [master, develop]
+
+jobs:
+ render:
+ strategy:
+ fail-fast: false
+ matrix:
+ os: [windows-latest, ubuntu-latest, macos-latest]
+ runs-on: ${{ matrix.os }}
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-dotnet@v4
+ with:
+ dotnet-version: |
+ 10.0.x
+ 11.0.x
+ - name: Install Graphviz on Windows
+ if: runner.os == 'Windows'
+ run: choco install graphviz --no-progress -y
+ - name: Install Graphviz on Linux
+ if: runner.os == 'Linux'
+ run: sudo apt-get update && sudo apt-get install -y graphviz
+ - name: Install Graphviz on macOS
+ if: runner.os == 'macOS'
+ run: brew install graphviz
+ - name: Test rendering
+ shell: pwsh
+ run: |
+ if ($IsWindows) {
+ $env:GRAPHVIZ_DOT = 'C:\Program Files\Graphviz\bin\dot.exe'
+ } else {
+ $env:GRAPHVIZ_DOT = 'dot'
+ }
+ dotnet test source/Lite.StateMachine.DotGraph.Tests -c Release --verbosity normal
+ - name: Pack standalone renderer
+ run: dotnet pack source/Lite.StateMachine.DotGraph -c Release --no-build
diff --git a/Lite.StateMachine.slnx b/Lite.StateMachine.slnx
index a57be99..1ec63a7 100644
--- a/Lite.StateMachine.slnx
+++ b/Lite.StateMachine.slnx
@@ -7,6 +7,7 @@
+
@@ -20,8 +21,10 @@
+
+
diff --git a/readme.md b/readme.md
index 2c88b08..318c7a1 100644
--- a/readme.md
+++ b/readme.md
@@ -142,9 +142,24 @@ public class BasicState3() : BaseState
### Generate DOT Graph (GraphViz)
```cs
-var uml = machine.ExportUml(includeSubmachines: true);
+var uml = machine.ExportUml();
```
+To generate SVG or PNG files from DOT, use the optional
+[Lite.StateMachine.DotGraph](source/Lite.StateMachine.DotGraph/readme.md) package:
+
+```cs
+using Lite.StateMachine.DotGraph;
+
+var renderer = new GraphvizRenderer();
+await renderer.RenderAsync(machine.ExportUml(), "machine.svg");
+await renderer.RenderFileAsync("machine.dot", "machine.png", DotGraphFormat.Png);
+```
+
+The renderer requires an installed or application-supplied [Graphviz](https://graphviz.org/download/)
+executable. It is independent of the core library and uses portable .NET process APIs
+for Windows, Linux, and macOS. See the package README for deployment requirements.
+

### Composite States
diff --git a/samples/Sample11.GenerateDotGraph/.gitignore b/samples/Sample11.GenerateDotGraph/.gitignore
new file mode 100644
index 0000000..1de3a3e
--- /dev/null
+++ b/samples/Sample11.GenerateDotGraph/.gitignore
@@ -0,0 +1,3 @@
+*.png
+*.svg
+*.dot
diff --git a/samples/Sample11.GenerateDotGraph/Generate-Diagrams.ps1 b/samples/Sample11.GenerateDotGraph/Generate-Diagrams.ps1
new file mode 100644
index 0000000..c69ac52
--- /dev/null
+++ b/samples/Sample11.GenerateDotGraph/Generate-Diagrams.ps1
@@ -0,0 +1,66 @@
+<#
+.SYNOPSIS
+Builds the sample, loads its DLL, and renders the same diagrams as the console app.
+.EXAMPLE
+./Generate-Diagrams.ps1 -DotPath 'C:/Program Files/Graphviz/bin/dot.exe'
+#>
+#Requires -Version 7.0
+
+[CmdletBinding()]
+param(
+ [string] $OutputDirectory = (Join-Path $PSScriptRoot 'diagrams'),
+ [string] $DotPath = 'dot',
+ [ValidateSet('Debug', 'Release')]
+ [string] $Configuration = 'Release',
+ [switch] $SkipBuild
+)
+
+Set-StrictMode -Version Latest
+$ErrorActionPreference = 'Stop'
+
+if ([Environment]::Version.Major -lt 10) {
+ throw 'Use PowerShell hosted on .NET 10 or later (for example PowerShell 7.6). Windows PowerShell 5.1 is not supported.'
+}
+
+$project = Join-Path $PSScriptRoot 'Sample11.GenerateDotGraph.csproj'
+if (-not $SkipBuild) {
+ dotnet build $project -c $Configuration -f net10.0
+ if ($LASTEXITCODE -ne 0) {
+ throw 'Sample build failed.'
+ }
+}
+
+# Matches this repository's Directory.Build.props output layout.
+$assemblyDirectory = [IO.Path]::GetFullPath(
+ (Join-Path $PSScriptRoot "../../output/Sample11.GenerateDotGraph/$Configuration/net10.0"))
+
+foreach ($assemblyName in @('Lite.StateMachine.dll', 'Lite.StateMachine.DotGraph.dll', 'Sample11.GenerateDotGraph.dll'))
+{
+ $assemblyPath = Join-Path $assemblyDirectory $assemblyName
+ if (-not (Test-Path -LiteralPath $assemblyPath -PathType Leaf)) {
+ throw "Assembly not found: $assemblyPath. Build the sample first or omit -SkipBuild."
+ }
+ [void][Reflection.Assembly]::LoadFrom($assemblyPath)
+}
+
+$OutputDirectory = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($OutputDirectory)
+[void][IO.Directory]::CreateDirectory($OutputDirectory)
+$renderer = [Lite.StateMachine.DotGraph.GraphvizRenderer]::new($DotPath, [TimeSpan]::FromSeconds(30))
+$token = [Threading.CancellationToken]::None
+
+foreach ($includeLegend in @($false, $true)) {
+ $name = if ($includeLegend) { 'machine-legend' } else { 'machine' }
+
+ # This calls a public DLL method, not the console application's entry point.
+ $dot = [Sample11.GenerateDotGraph.WorkflowDiagram]::ExportDot($includeLegend)
+
+ [IO.File]::WriteAllText((Join-Path $OutputDirectory "$name.dot"), $dot)
+
+ [void]$renderer.RenderAsync($dot, (Join-Path $OutputDirectory "$name.svg"),
+ [Lite.StateMachine.DotGraph.DotGraphFormat]::Svg, $token).GetAwaiter().GetResult()
+
+ [void]$renderer.RenderAsync($dot, (Join-Path $OutputDirectory "$name.png"),
+ [Lite.StateMachine.DotGraph.DotGraphFormat]::Png, $token).GetAwaiter().GetResult()
+
+ Write-Output "Generated $name.dot, $name.svg, and $name.png in $OutputDirectory"
+}
diff --git a/samples/Sample11.GenerateDotGraph/Program.cs b/samples/Sample11.GenerateDotGraph/Program.cs
new file mode 100644
index 0000000..acf8488
--- /dev/null
+++ b/samples/Sample11.GenerateDotGraph/Program.cs
@@ -0,0 +1,48 @@
+// Copyright Xeno Innovations, Inc. 2026
+// See the LICENSE file in the project root for more information.
+
+using System;
+using System.IO;
+using System.Threading.Tasks;
+using Lite.StateMachine.DotGraph;
+
+namespace Sample11.GenerateDotGraph;
+
+internal static class Program
+{
+ private static async Task Main(string[] args)
+ {
+ if (args.Length > 2)
+ {
+ Console.Error.WriteLine("Usage: Sample11.GenerateDotGraph [output-directory] [dot-executable]");
+ return 1;
+ }
+
+ var outputDirectory = Path.GetFullPath(args.Length > 0
+ ? args[0]
+ : Path.Combine(AppContext.BaseDirectory, "diagrams"));
+
+ var renderer = new GraphvizRenderer(args.Length > 1
+ ? args[1]
+ : "dot");
+
+ Directory.CreateDirectory(outputDirectory);
+
+ foreach (var includeLegend in new[] { false, true })
+ {
+ var name = includeLegend ? "machine-legend" : "machine";
+
+ // Create state machine and export DOT graph without running any states.
+ var dot = SampleStateMachine.ExportDot(includeLegend);
+ var dotPath = Path.Combine(outputDirectory, name + ".dot");
+
+ await File.WriteAllTextAsync(dotPath, dot);
+ await renderer.RenderAsync(dot, Path.Combine(outputDirectory, name + ".svg"));
+ await renderer.RenderAsync(dot, Path.Combine(outputDirectory, name + ".png"), DotGraphFormat.Png);
+
+ Console.WriteLine($"Generated {name}.dot, {name}.svg, and {name}.png in {outputDirectory}");
+ }
+
+ return 0;
+ }
+}
diff --git a/samples/Sample11.GenerateDotGraph/Sample11.GenerateDotGraph.csproj b/samples/Sample11.GenerateDotGraph/Sample11.GenerateDotGraph.csproj
new file mode 100644
index 0000000..49c78a9
--- /dev/null
+++ b/samples/Sample11.GenerateDotGraph/Sample11.GenerateDotGraph.csproj
@@ -0,0 +1,14 @@
+
+
+ Exe
+ false
+ net10.0
+ disable
+ enable
+
+
+
+
+
+
+
diff --git a/samples/Sample11.GenerateDotGraph/SampleStateMachine.cs b/samples/Sample11.GenerateDotGraph/SampleStateMachine.cs
new file mode 100644
index 0000000..8f39f7c
--- /dev/null
+++ b/samples/Sample11.GenerateDotGraph/SampleStateMachine.cs
@@ -0,0 +1,59 @@
+// Copyright Xeno Innovations, Inc. 2026
+// See the LICENSE file in the project root for more information.
+
+using System;
+using Lite.StateMachine;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Logging;
+
+namespace Sample11.GenerateDotGraph;
+
+/// Exports the same topology as DiMsTests.Basic_GeneratesExportUml_SuccessTestAsync.
+public static class SampleStateMachine
+{
+ /// Builds the configured machine and exports DOT without running any states.
+ /// Whether to add the Graphviz legend.
+ /// DOT text with Entry as the initial state.
+ public static string ExportDot(bool includeLegend)
+ {
+ // Configure DI
+ using var services = new ServiceCollection()
+ .AddLogging(builder => builder.AddSimpleConsole())
+ .AddSingleton()
+ .AddTransient()
+ .AddTransient()
+ .AddTransient()
+ .AddTransient()
+ .AddTransient()
+ .AddTransient()
+ .AddTransient()
+ .BuildServiceProvider();
+
+ // Factory uses DI to construct states
+ var aggregator = services.GetRequiredService();
+ Func factory = type => ActivatorUtilities.CreateInstance(services, type);
+
+ // Create State Machine
+ var machine = new StateMachine(factory, aggregator);
+
+ machine.RegisterState(CompositeMsgStateId.Entry, CompositeMsgStateId.Parent);
+ machine.RegisterComposite(
+ stateId: CompositeMsgStateId.Parent,
+ initialChildStateId: CompositeMsgStateId.Parent_Fetch,
+ onSuccess: CompositeMsgStateId.Done,
+ onError: CompositeMsgStateId.Error,
+ onFailure: CompositeMsgStateId.Failure);
+
+ //// Substates of ParentState
+ machine.RegisterSubState(CompositeMsgStateId.Parent_Fetch, CompositeMsgStateId.Parent, CompositeMsgStateId.Parent_WaitMessage);
+ machine.RegisterSubState(CompositeMsgStateId.Parent_WaitMessage, CompositeMsgStateId.Parent);
+
+ // End of substates
+ machine.RegisterState(CompositeMsgStateId.Done);
+ machine.RegisterState(CompositeMsgStateId.Error, CompositeMsgStateId.Parent);
+ machine.RegisterState(CompositeMsgStateId.Failure, CompositeMsgStateId.Parent);
+
+ // Export the DOT graph with Entry as the initial state.
+ return machine.ExportUml([CompositeMsgStateId.Entry], includeLegend: includeLegend);
+ }
+}
diff --git a/samples/Sample11.GenerateDotGraph/WorkflowStates.cs b/samples/Sample11.GenerateDotGraph/WorkflowStates.cs
new file mode 100644
index 0000000..c090912
--- /dev/null
+++ b/samples/Sample11.GenerateDotGraph/WorkflowStates.cs
@@ -0,0 +1,65 @@
+// Copyright Xeno Innovations, Inc. 2026
+// See the LICENSE file in the project root for more information.
+
+using System.Threading.Tasks;
+using Lite.StateMachine;
+using Microsoft.Extensions.Logging;
+
+namespace Sample11.GenerateDotGraph;
+
+#pragma warning disable SA1402 // Keep the small diagram-only state definitions together.
+#pragma warning disable SA1649 // File groups related state definitions.
+
+/// State identifiers matching the composite export test.
+public enum CompositeMsgStateId
+{
+ Entry,
+ Parent,
+ Parent_Fetch,
+ Parent_WaitMessage,
+ Done,
+ Error,
+ Failure,
+}
+
+public sealed class EntryState(ILogger logger) : DiagramState(logger);
+
+public sealed class ParentState(ILogger logger) : DiagramState(logger);
+
+public sealed class ParentSub_FetchState(ILogger logger) : DiagramState(logger);
+
+public sealed class ParentSub_WaitMessageState(ILogger logger)
+ : DiagramState(logger), ICommandState
+{
+ public Task OnMessage(Context context, object message) => Task.CompletedTask;
+
+ public Task OnTimeout(Context context)
+ {
+ context.NextState(Result.Failure);
+ return Task.CompletedTask;
+ }
+}
+
+public sealed class DoneState(ILogger logger) : DiagramState(logger);
+
+public sealed class ErrorState(ILogger logger) : DiagramState(logger);
+
+public sealed class FailureState(ILogger logger) : DiagramState(logger);
+
+/// Minimal state behavior; diagram generation never executes these handlers.
+public abstract class DiagramState(ILogger logger) : IState
+{
+ public Task OnEnter(Context context)
+ {
+ logger.LogInformation("Entered {StateId}", context.CurrentStateId);
+ context.NextState(Result.Success);
+ return Task.CompletedTask;
+ }
+
+ public Task OnEntering(Context context) => Task.CompletedTask;
+
+ public Task OnExit(Context context) => Task.CompletedTask;
+}
+
+#pragma warning restore SA1649 // File groups related state definitions.
+#pragma warning restore SA1402 // Keep the small diagram-only state definitions together.
diff --git a/samples/Sample11.GenerateDotGraph/readme.md b/samples/Sample11.GenerateDotGraph/readme.md
new file mode 100644
index 0000000..1977b62
--- /dev/null
+++ b/samples/Sample11.GenerateDotGraph/readme.md
@@ -0,0 +1,67 @@
+# Sample 11: Generate DOT, SVG, and PNG diagrams
+
+This sample uses `Lite.StateMachine.DotGraph` to render the same topology as
+`Basic_GeneratesExportUml_SuccessTestAsync` in `DiMsTests.cs`:
+
+* `Entry` transitions to the composite `Parent` state.
+* `Parent` starts at `Parent_Fetch`, which transitions to `Parent_WaitMessage`.
+* `Parent` has `Success`, `Error`, and `Failure` transitions to `Done`, `Error`, and `Failure`.
+* `Error` and `Failure` transition back to `Parent`;
+* `Done` is the terminal final state.
+
+The DI factory, state identifiers, transition registrations, initial Entry marker,
+and legend options match the test. State handlers are minimal diagram-only examples;
+the test's message service, counters, and workflow execution are not needed to export
+the topology. Neither generation path runs the workflow.
+
+## Requirements
+
+* Install .NET 10 or 11
+* Install [Graphviz](https://graphviz.org/download/).
+* Add Graphviz's `bin` directory to PATH, or pass its `dot`/`dot.exe` path explicitly.
+
+The project references the local core and renderer projects; it does not reference
+or reuse the unit-test assembly.
+
+## Console application
+
+From the repository root:
+
+```powershell
+dotnet run --project samples/Sample11.GenerateDotGraph -c Release -f net10.0 -- samples/Sample11.GenerateDotGraph/diagrams
+
+# Optional second argument: the Graphviz executable (quote paths with spaces).
+dotnet run --project samples/Sample11.GenerateDotGraph -c Release -f net10.0 -- samples/Sample11.GenerateDotGraph/diagrams 'C:/Program Files/Graphviz/bin/dot.exe'
+```
+
+Use `-f net11.0` to run on .NET 11. With no application arguments, diagrams are
+written to a `diagrams` directory beside the built executable.
+
+## External PowerShell generation
+
+Use PowerShell hosted on .NET 10 or later, such as PowerShell 7.6.
+Run a fresh process to avoid conflicts with previously loaded DLL versions:
+
+```powershell
+pwsh -NoProfile -File samples/Sample11.GenerateDotGraph/Generate-Diagrams.ps1
+
+# Optional output folder and Graphviz path:
+pwsh -NoProfile -File samples/Sample11.GenerateDotGraph/Generate-Diagrams.ps1 -OutputDirectory ./output/sample11-powershell -DotPath 'C:/Program Files/Graphviz/bin/dot.exe'
+```
+
+The script builds `net10.0`, loads the sample DLL and its libraries, and calls
+`WorkflowDiagram.ExportDot(bool)` directly. It then renders the returned DOT through
+`GraphvizRenderer`; it does not launch the sample executable. `-SkipBuild` reuses a
+previous build, and `-Configuration Debug` selects Debug output instead of Release.
+By default, the script writes to this sample's `diagrams` directory.
+
+Both generation paths produce six files, replacing existing images on success:
+
+| Version | DOT | SVG | PNG |
+| --- | --- | --- | --- |
+| Without legend | `machine.dot` | `machine.svg` | `machine.png` |
+| With legend | `machine-legend.dot` | `machine-legend.svg` | `machine-legend.png` |
+
+The checked-in `diagrams` directory contains generated examples. DOT text is the
+same from both paths; image layout may vary with the installed Graphviz version
+and fonts.
diff --git a/source/Lite.StateMachine.DotGraph.Tests/GraphvizRendererTests.cs b/source/Lite.StateMachine.DotGraph.Tests/GraphvizRendererTests.cs
new file mode 100644
index 0000000..b10a9d6
--- /dev/null
+++ b/source/Lite.StateMachine.DotGraph.Tests/GraphvizRendererTests.cs
@@ -0,0 +1,163 @@
+// Copyright Xeno Innovations, Inc. 2026
+// See the LICENSE file in the project root for more information.
+
+using System;
+using System.IO;
+using System.Text;
+using System.Threading;
+using System.Threading.Tasks;
+using Lite.StateMachine.DotGraph;
+
+[assembly: Parallelize(Scope = ExecutionScope.MethodLevel)]
+
+namespace Lite.StateMachine.DotGraph.Tests;
+
+[TestClass]
+public sealed class GraphvizRendererTests
+{
+ private const string Graph = "digraph { subgraph cluster_child { label=\"Child\"; a [label=\"Prépare\"]; a -> b [label=\"Success\"]; } b -> c [label=\"Failure\"]; }";
+ private readonly string _directory = Path.Combine(Path.GetTempPath(), "DotGraph tests " + Guid.NewGuid());
+
+ [TestCleanup]
+ public void Cleanup()
+ {
+ if (Directory.Exists(_directory))
+ Directory.Delete(_directory, recursive: true);
+ }
+
+ [TestMethod]
+ public async Task MissingExecutableExplainsInstallationAsync()
+ {
+ var renderer = new GraphvizRenderer(Path.Combine(_directory, "missing-dot"));
+ var exception = await Assert.ThrowsAsync(() => renderer.RenderAsync(Graph, Output("machine.svg")));
+ StringAssert.Contains(exception.Message, "Install Graphviz");
+ Assert.IsEmpty(Directory.GetFiles(_directory));
+ }
+
+ [TestMethod]
+ public async Task ValidationRejectsInvalidArgumentsBeforeStartingGraphvizAsync()
+ {
+ Assert.Throws(() => new GraphvizRenderer(" "));
+ Assert.Throws(() => new GraphvizRenderer(timeout: TimeSpan.Zero));
+ var renderer = new GraphvizRenderer("missing-dot");
+ Assert.Throws(() => renderer.RenderAsync(" ", Output("machine.svg")));
+ await Assert.ThrowsAsync(() => renderer.RenderAsync(Graph, Output("machine.svg"), (DotGraphFormat)99));
+ Assert.Throws(() => renderer.RenderFileAsync(Output("missing.dot"), Output("machine.svg")));
+ Directory.CreateDirectory(_directory);
+ var input = Output("machine.dot");
+ await File.WriteAllTextAsync(input, Graph);
+ Assert.Throws(() => renderer.RenderFileAsync(input, input));
+ Assert.AreEqual(Graph, await File.ReadAllTextAsync(input));
+ }
+
+ [TestMethod]
+ public async Task PreCanceledRequestDoesNotCreateOutputAsync()
+ {
+ using var cancellation = new CancellationTokenSource();
+ cancellation.Cancel();
+ await Assert.ThrowsAsync(() => new GraphvizRenderer().RenderAsync(Graph, Output("machine.svg"), cancellationToken: cancellation.Token));
+ Assert.IsFalse(Directory.Exists(_directory));
+ }
+
+ [TestMethod]
+ [TestCategory("Graphviz")]
+ public async Task RendersTextAsUtf8SvgAndReplacesExistingImageAsync()
+ {
+ var renderer = CreateRenderer();
+ var output = Output("nested [states]/machine ü.svg");
+ await renderer.RenderAsync(Graph, output);
+ var svg = await File.ReadAllTextAsync(output);
+ StringAssert.Contains(svg, "