mcpField
D
dotnet-mermaid-diagrams

dotnet-mermaid-diagrams

github.com/wshaddix開発8669 回インストール35 週間前に更新
リポジトリ

dotnet-mermaid-diagrams について

.NET プロジェクト向けの Mermaid 図表リファレンスで、アーキテクチャ、シーケンス、クラス、デプロイ、ER、状態、フローチャートのパターンと構文規約を扱います。プロジェクト文書の図表を作成・保守する開発者向けです。

主な機能

  1. 01一般的な Mermaid 図表の種類を網羅
  2. 02.NET のアーキテクチャとコード例
  3. 03図表の命名・グループ化規約
  4. 04GitHub 表示とダークモードの注意点

活用シーン

  1. 01サービス構成やマイクロサービスのトポロジーを図示
  2. 02API リクエストや認証フローを表示
  3. 03EF Core モデルとデータベース関係を可視化
  4. 04デプロイ構成や CI/CD フローを文書化

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/wshaddix/dotnet-skills --skill dotnet-mermaid-diagrams

インストール後、Claude Code で/dotnet-mermaid-diagramsを入力して読み込まれたか確認します。

詳細

dotnet-mermaid-diagrams

.NET プロジェクト向け Mermaid 図のリファレンス:アーキテクチャ図(C4 スタイルのコンテキスト図、コンテナー図、コンポーネント図、レイヤードアーキテクチャ、マイクロサービスのトポロジー)、シーケンス図(API リクエストフロー、async/await パターン、ミドルウェアパイプライン、認証フロー)、クラス図(ドメインモデル、DI 登録グラフ、継承階層、インターフェイスの実装)、デプロイ図(コンテナーのデプロイ、Kubernetes の Pod 配置、CI/CD パイプラインフロー)、ER 図(EF Core モデルのリレーションシップ、データベーススキーマの可視化)、状態図(ワークフローの状態、注文処理、Saga パターン、ステートマシンパターン)、フローチャート(意思決定ツリー、フレームワークの選定、アーキテクチャの選択肢)を扱います。命名、グループ化、GitHub でのレンダリング、ダークモードへの配慮といった、図をコードとして記述するための規約も含まれています。

バージョンの前提: Mermaid v10 以降(GitHub、Starlight、Docusaurus でネイティブにサポートされています)。GitHub は Markdown ファイル、Issue、PR、ディスカッションで Mermaid をレンダリングします。コード例の基準は .NET 8.0 以降です。

対象範囲の境界: このスキルは、Mermaid 図の構文と .NET 固有の図のパターン、つまり実際の図の内容、規約、レンダリングのヒントを担当します。Mermaid レンダリングに関するドキュメントプラットフォームのセットアップ(Starlight プラグイン、Docusaurus テーマ、DocFX テンプレート)は [skill:dotnet-documentation-strategy] が担当します。GitHub ネイティブのドキュメント構成(README、CONTRIBUTING、テンプレート)は [skill:dotnet-github-docs] が担当します。

対象外: Mermaid レンダリングに関するドキュメントプラットフォームの構成については、[skill:dotnet-documentation-strategy] を参照してください。図を埋め込む GitHub ネイティブのドキュメント構成と README のパターンについては、[skill:dotnet-github-docs] を参照してください。図を含むドキュメントサイトの CI/CD パイプラインによるデプロイについては、[skill:dotnet-gha-deploy] を参照してください。

相互参照:[skill:dotnet-documentation-strategy] では各種ドキュメントプラットフォームでの Mermaid レンダリングのセットアップ、[skill:dotnet-github-docs] では GitHub ネイティブのドキュメントへの図の埋め込み、[skill:dotnet-gha-deploy] ではドキュメントサイトのデプロイを扱います。


アーキテクチャ図

C4 スタイルのコンテキスト図

外部のアクターやシステムを含む、システムの環境を示します。

graph TB
    User["End User<br/>(Browser/Mobile)"]
    Admin["Admin<br/>(Internal)"]

    subgraph System["My .NET Application"]
        API["ASP.NET Core API<br/>(.NET 8)"]
    end

    ExtAuth["Identity Provider<br/>(Azure AD / Auth0)"]
    ExtEmail["Email Service<br/>(SendGrid)"]
    ExtPay["Payment Gateway<br/>(Stripe)"]

    User -->|"HTTPS"| API
    Admin -->|"HTTPS"| API
    API -->|"OAuth 2.0"| ExtAuth
    API -->|"SMTP/API"| ExtEmail
    API -->|"REST API"| ExtPay
C4 スタイルのコンテナー図

大まかな技術選択と、それらの相互作用を示します。

graph TB
    subgraph Client["Client Tier"]
        SPA["Blazor WASM<br/>(WebAssembly)"]
        Mobile["MAUI App<br/>(.NET 8)"]
    end

    subgraph API_Tier["API Tier"]
        Gateway["API Gateway<br/>(YARP)"]
        OrderAPI["Order Service<br/>(ASP.NET Core)"]
        CatalogAPI["Catalog Service<br/>(ASP.NET Core)"]
        IdentityAPI["Identity Service<br/>(Duende IdentityServer)"]
    end

    subgraph Data_Tier["Data Tier"]
        OrderDB[("Order DB<br/>(SQL Server)")]
        CatalogDB[("Catalog DB<br/>(PostgreSQL)")]
        Cache[("Redis Cache")]
        Bus["Message Bus<br/>(RabbitMQ)"]
    end

    SPA -->|"HTTPS"| Gateway
    Mobile -->|"HTTPS"| Gateway
    Gateway --> OrderAPI
    Gateway --> CatalogAPI
    Gateway --> IdentityAPI
    OrderAPI --> OrderDB
    OrderAPI --> Cache
    OrderAPI --> Bus
    CatalogAPI --> CatalogDB
    CatalogAPI --> Cache
    Bus --> CatalogAPI
C4 スタイルのコンポーネント図

単一サービスの内部構造を示します。

graph TB
    subgraph OrderService["Order Service"]
        Controllers["Controllers<br/>(API Endpoints)"]
        Validators["FluentValidation<br/>(Request Validators)"]
        Handlers["MediatR Handlers<br/>(Business Logic)"]
        DomainModels["Domain Models<br/>(Entities, Value Objects)"]
        Repos["Repositories<br/>(EF Core)"]
        Events["Domain Events<br/>(MediatR Notifications)"]
        IntEvents["Integration Events<br/>(MassTransit)"]
    end

    Controllers --> Validators
    Controllers --> Handlers
    Handlers --> DomainModels
    Handlers --> Repos
    Handlers --> Events
    Events --> IntEvents
レイヤードアーキテクチャ
graph TB
    subgraph Presentation["Presentation Layer"]
        API["ASP.NET Core Controllers / Minimal APIs"]
        Blazor["Blazor Components"]
    end

    subgraph Application["Application Layer"]
        Services["Application Services"]
        DTOs["DTOs / View Models"]
        Mappings["AutoMapper Profiles"]
        CQRS["MediatR Handlers"]
    end

    subgraph Domain["Domain Layer"]
        Entities["Entities"]
        ValueObjects["Value Objects"]
        DomainEvents["Domain Events"]
        Interfaces["Repository Interfaces"]
    end

    subgraph Infrastructure["Infrastructure Layer"]
        EFCore["EF Core DbContext"]
        Repositories["Repository Implementations"]
        ExternalServices["External Service Clients"]
        Messaging["MassTransit / RabbitMQ"]
    end

    Presentation --> Application
    Application --> Domain
    Infrastructure --> Domain
    Infrastructure -.->|"implements"| Interfaces
マイクロサービスのトポロジー
graph LR
    subgraph Ingress
        LB["Load Balancer"]
        GW["API Gateway<br/>(YARP)"]
    end

    subgraph Services
        S1["Order Service"]
        S2["Catalog Service"]
        S3["Identity Service"]
        S4["Notification Service"]
    end

    subgraph Messaging
        MQ["RabbitMQ"]
    end

    subgraph Observability
        SEQ["Seq / ELK"]
        OTEL["OpenTelemetry Collector"]
    end

    LB --> GW
    GW --> S1
    GW --> S2
    GW --> S3
    S1 -->|"publish"| MQ
    MQ -->|"subscribe"| S2
    MQ -->|"subscribe"| S4
    S1 -.->|"traces"| OTEL
    S2 -.->|"traces"| OTEL
    S1 -.->|"logs"| SEQ
    S2 -.->|"logs"| SEQ

シーケンス図

API リクエストフロー
sequenceDiagram
    participant Client
    participant Middleware as ASP.NET Middleware
    participant Auth as Authentication
    participant Controller
    participant Service
    participant DB as Database

    Client->>Middleware: POST /api/orders
    Middleware->>Auth: Validate JWT
    Auth-->>Middleware: Claims Principal
    Middleware->>Controller: OrdersController.Create()
    Controller->>Service: CreateOrderAsync(dto)
    Service->>DB: INSERT INTO Orders
    DB-->>Service: Order entity
    Service-->>Controller: OrderResponse
    Controller-->>Client: 201 Created
Async/Await パターン
sequenceDiagram
    participant Caller
    participant Service as OrderService
    participant Repo as IOrderRepository
    participant DB as SQL Server
    participant Cache as Redis

    Caller->>+Service: GetOrderAsync(id)
    Service->>+Cache: GetAsync(key)
    Cache-->>-Service: null (cache miss)
    Service->>+Repo: FindByIdAsync(id)
    Repo->>+DB: SELECT ... WHERE Id = @id
    Note over Repo,DB: await - thread returned to pool
    DB-->>-Repo: Row data
    Repo-->>-Service: Order entity
    Service->>+Cache: SetAsync(key, order, expiry)
    Note over Service,Cache: Fire-and-forget or await
    Cache-->>-Service: OK
    Service-->>-Caller: Order
ミドルウェアパイプライン
sequenceDiagram
    participant Client
    participant ExHandler as ExceptionHandler
    participant HSTS as HSTS Middleware
    participant Auth as Authentication
    participant Authz as Authorization
    participant CORS as CORS Middleware
    participant Routing as Routing
    participant Endpoint

    Client->>ExHandler: HTTP Request
    ExHandler->>HSTS: next()
    HSTS->>Auth: next()
    Auth->>Authz: next()
    Authz->>CORS: next()
    CORS->>Routing: next()
    Routing->>Endpoint: Matched endpoint
    Endpoint-->>Routing: Response
    Routing-->>CORS: Response
    CORS-->>Authz: Response
    Authz-->>Auth: Response
    Auth-->>HSTS: Response
    HSTS-->>ExHandler: Response
    ExHandler-->>Client: HTTP Response
認証フロー(OAuth 2.0 / OIDC)
sequenceDiagram
    participant User
    participant App as Blazor App
    participant BFF as BFF (ASP.NET Core)
    participant IDP as Identity Provider
    participant API as Protected API

    User->>App: Navigate to protected page
    App->>BFF: GET /api/user (no cookie)
    BFF-->>App: 401 Unauthorized
    App->>BFF: GET /login
    BFF->>IDP: Authorization Code + PKCE
    IDP->>User: Login page
    User->>IDP: Credentials
    IDP->>BFF: Authorization code
    BFF->>IDP: Exchange code for tokens
    IDP-->>BFF: Access + Refresh + ID tokens
    BFF-->>App: Set-Cookie (session)
    App->>BFF: GET /api/orders (with cookie)
    BFF->>API: GET /api/orders (Bearer token)
    API-->>BFF: Order data
    BFF-->>App: Order data

クラス図

ドメインモデル
classDiagram
    class Order {
        +Guid Id
        +DateTime CreatedAt
        +OrderStatus Status
        +decimal TotalAmount
        +List~OrderLine~ Lines
        +AddLine(product, quantity)
        +Submit()
        +Cancel(reason)
    }

    class OrderLine {
        +Guid Id
        +Guid ProductId
        +string ProductName
        +int Quantity
        +decimal UnitPrice
        +decimal LineTotal
    }

    class OrderStatus {
        <<enumeration>>
        Draft
        Submitted
        Processing
        Shipped
        Delivered
        Cancelled
    }

    class Customer {
        +Guid Id
        +string Name
        +string Email
        +Address ShippingAddress
        +List~Order~ Orders
    }

    class Address {
        <<value object>>
        +string Street
        +string City
        +string State
        +string PostalCode
        +string Country
    }

    Order "1" --> "*" OrderLine : contains
    Order --> OrderStatus : has
    Customer "1" --> "*" Order : places
    Customer --> Address : has
DI 登録グラフ
graph TB
    subgraph Singleton
        S1["IConfiguration"]
        S2["IMemoryCache"]
        S3["IHttpClientFactory"]
    end

    subgraph Scoped["Scoped (per-request)"]
        SC1["DbContext"]
        SC2["IOrderRepository"]
        SC3["ICurrentUser"]
    end

    subgraph Transient
        T1["IValidator~CreateOrderCommand~"]
        T2["INotificationSender"]
    end

    SC2 -->|"depends on"| SC1
    SC2 -->|"depends on"| S2
    T2 -->|"depends on"| S3
    SC3 -->|"depends on"| S1

    style Singleton fill:#e1f5fe
    style Scoped fill:#f3e5f5
    style Transient fill:#fff3e0
インターフェイスの実装階層
classDiagram
    class IRepository~T~ {
        <<interface>>
        +GetByIdAsync(id) Task~T~
        +ListAsync() Task~List~T~~
        +AddAsync(entity) Task
        +UpdateAsync(entity) Task
        +DeleteAsync(id) Task
    }

    class IOrderRepository {
        <<interface>>
        +GetByCustomerAsync(customerId) Task~List~Order~~
        +GetPendingAsync() Task~List~Order~~
    }

    class RepositoryBase~T~ {
        <<abstract>>
        #DbContext _context
        +GetByIdAsync(id) Task~T~
        +ListAsync() Task~List~T~~
        +AddAsync(entity) Task
        +UpdateAsync(entity) Task
        +DeleteAsync(id) Task
    }

    class OrderRepository {
        +GetByCustomerAsync(customerId) Task~List~Order~~
        +GetPendingAsync() Task~List~Order~~
    }

    IRepository~T~ <|.. RepositoryBase~T~ : implements
    IOrderRepository <|.. OrderRepository : implements
    RepositoryBase~T~ <|-- OrderRepository : extends
    IRepository~T~ <|-- IOrderRepository : extends

デプロイ図

コンテナーのデプロイ
graph TB
    subgraph Host["Docker Host / VM"]
        subgraph AppContainer["App Container"]
            App["ASP.NET Core App<br/>mcr.microsoft.com/dotnet/aspnet:8.0"]
        end

        subgraph DBContainer["Database Container"]
            DB["SQL Server<br/>mcr.microsoft.com/mssql/server:2022"]
        end

        subgraph CacheContainer["Cache Container"]
            Redis["Redis<br/>redis:7-alpine"]
        end

        subgraph ReverseProxy["Reverse Proxy"]
            Nginx["Nginx<br/>(SSL termination)"]
        end
    end

    Internet["Internet"] -->|"443"| Nginx
    Nginx -->|"8080"| App
    App -->|"1433"| DB
    App -->|"6379"| Redis
Kubernetes Pod の配置
graph TB
    subgraph Cluster["Kubernetes Cluster"]
        subgraph NS["namespace: myapp"]
            subgraph Deploy1["Deployment: order-api"]
                Pod1A["Pod<br/>order-api<br/>(replica 1)"]
                Pod1B["Pod<br/>order-api<br/>(replica 2)"]
            end

            subgraph Deploy2["Deployment: catalog-api"]
                Pod2A["Pod<br/>catalog-api<br/>(replica 1)"]
            end

            SVC1["Service: order-api-svc<br/>ClusterIP:80"]
            SVC2["Service: catalog-api-svc<br/>ClusterIP:80"]
            Ingress["Ingress Controller<br/>(nginx)"]
            CM["ConfigMap:<br/>appsettings"]
            Secret["Secret:<br/>connection-strings"]
        end
    end

    Internet["Internet"] --> Ingress
    Ingress -->|"/api/orders"| SVC1
    Ingress -->|"/api/catalog"| SVC2
    SVC1 --> Pod1A
    SVC1 --> Pod1B
    SVC2 --> Pod2A
    CM -.->|"mount"| Pod1A
    CM -.->|"mount"| Pod2A
    Secret -.->|"mount"| Pod1A
    Secret -.->|"mount"| Pod2A
CI/CD パイプラインフロー
graph LR
    subgraph Trigger
        Push["Push to main"]
        PR["Pull Request"]
        Tag["Version Tag"]
    end

    subgraph Build["Build Stage"]
        Restore["dotnet restore"]
        Compile["dotnet build"]
        Test["dotnet test"]
    end

    subgraph Package["Package Stage"]
        Pack["dotnet pack"]
        Publish["dotnet publish"]
        Docker["docker build"]
    end

    subgraph Deploy["Deploy Stage"]
        NuGet["Push to NuGet"]
        ACR["Push to ACR"]
        Staging["Deploy to Staging"]
        Prod["Deploy to Production"]
    end

    Push --> Restore
    PR --> Restore
    Tag --> Restore
    Restore --> Compile --> Test
    Test --> Pack
    Test --> Publish --> Docker
    Pack -->|"tag only"| NuGet
    Docker --> ACR
    ACR --> Staging
    Staging -->|"approval"| Prod

ER 図(EF Core モデル)

EF Core リレーションシップの可視化
erDiagram
    Customer ||--o{ Order : places
    Order ||--|{ OrderLine : contains
    OrderLine }o--|| Product : references
    Product }o--|| Category : "belongs to"
    Order ||--o| ShippingAddress : "ships to"
    Customer ||--o| CustomerProfile : has

    Customer {
        guid Id PK
        string Name
        string Email UK
        datetime CreatedAt
    }

    Order {
        guid Id PK
        guid CustomerId FK
        datetime OrderDate
        string Status
        decimal TotalAmount
    }

    OrderLine {
        guid Id PK
        guid OrderId FK
        guid ProductId FK
        int Quantity
        decimal UnitPrice
    }

    Product {
        guid Id PK
        guid CategoryId FK
        string Name
        string SKU UK
        decimal Price
        int StockQuantity
    }

    Category {
        guid Id PK
        string Name UK
        string Description
        guid ParentCategoryId FK "nullable, self-ref"
    }

    ShippingAddress {
        guid Id PK
        guid OrderId FK "unique"
        string Street
        string City
        string PostalCode
        string Country
    }

    CustomerProfile {
        guid Id PK
        guid CustomerId FK "unique"
        string AvatarUrl
        string Bio
    }
インデックスを含むデータベーススキーマ
erDiagram
    AuditLog {
        long Id PK "identity"
        string EntityType "indexed"
        guid EntityId "indexed"
        string Action
        string UserId FK "indexed"
        jsonb Changes
        datetime Timestamp "indexed, default GETUTCDATE()"
    }

    SoftDeleteEntity {
        guid Id PK
        string Name
        bool IsDeleted "global query filter"
        datetime DeletedAt "nullable"
        string DeletedBy "nullable"
    }

    TenantEntity {
        guid Id PK
        guid TenantId FK "global query filter, indexed"
        string Data
    }

状態図

注文処理ワークフロー
stateDiagram-v2
    [*] --> Draft : Create order

    Draft --> Submitted : Submit()
    Draft --> Cancelled : Cancel()

    Submitted --> PaymentPending : Process payment
    Submitted --> Cancelled : Cancel()

    PaymentPending --> PaymentFailed : Payment declined
    PaymentPending --> Paid : Payment confirmed

    PaymentFailed --> PaymentPending : Retry payment
    PaymentFailed --> Cancelled : Cancel()

    Paid --> Processing : Begin fulfillment
    Processing --> Shipped : Ship order
    Shipped --> Delivered : Confirm delivery

    Delivered --> [*]
    Cancelled --> [*]

    note right of PaymentPending
        Timeout after 30 minutes
        auto-transitions to PaymentFailed
    end note
Saga パターン(分散トランザクション)
stateDiagram-v2
    [*] --> OrderCreated : Start saga

    OrderCreated --> InventoryReserved : ReserveInventory
    OrderCreated --> OrderFailed : ReserveInventory failed

    InventoryReserved --> PaymentProcessed : ProcessPayment
    InventoryReserved --> InventoryReleased : ProcessPayment failed

    InventoryReleased --> OrderFailed : Compensate

    PaymentProcessed --> ShipmentScheduled : ScheduleShipment
    PaymentProcessed --> PaymentRefunded : ScheduleShipment failed

    PaymentRefunded --> InventoryReleased : Compensate

    ShipmentScheduled --> OrderCompleted : All steps succeeded
    OrderCompleted --> [*]
    OrderFailed --> [*]

    note left of InventoryReleased
        Compensation step:
        release reserved stock
    end note

    note left of PaymentRefunded
        Compensation step:
        refund payment
    end note
ステートマシンパターン(MassTransit)
stateDiagram-v2
    [*] --> New

    state "Awaiting Validation" as Validating
    state "Awaiting Payment" as AwaitingPayment
    state "Payment Failed" as PaymentFailed

    New --> Validating : OrderSubmitted event
    Validating --> AwaitingPayment : OrderValidated event
    Validating --> Cancelled : ValidationFailed event

    AwaitingPayment --> Confirmed : PaymentReceived event
    AwaitingPayment --> PaymentFailed : PaymentDeclined event

    PaymentFailed --> AwaitingPayment : PaymentRetried event
    PaymentFailed --> Cancelled : MaxRetriesExceeded

    Confirmed --> Shipped : OrderShipped event
    Shipped --> Completed : OrderDelivered event

    Completed --> [*]
    Cancelled --> [*]

フローチャート

フレームワーク選定の意思決定ツリー
flowchart TD
    Start["New .NET Project"] --> WebOrDesktop{"Web or Desktop?"}

    WebOrDesktop -->|"Web"| APIOnly{"API only?"}
    WebOrDesktop -->|"Desktop"| DesktopPlatform{"Target platforms?"}

    APIOnly -->|"Yes"| MinimalOrMVC{"Preference?"}
    APIOnly -->|"No, needs UI"| UIFramework{"Server or Client rendering?"}

    MinimalOrMVC -->|"Simple, few endpoints"| MinimalAPI["Minimal APIs"]
    MinimalOrMVC -->|"Complex, many controllers"| MVC["ASP.NET Core MVC/API"]

    UIFramework -->|"Server"| BlazorServer["Blazor Server / SSR"]
    UIFramework -->|"Client"| BlazorWASM["Blazor WebAssembly"]
    UIFramework -->|"Both"| BlazorAuto["Blazor Auto (SSR + WASM)"]

    DesktopPlatform -->|"Windows only"| WPFOrWinUI{"Modern UI needed?"}
    DesktopPlatform -->|"Cross-platform"| MAUI["MAUI"]

    WPFOrWinUI -->|"Legacy compat"| WPF["WPF"]
    WPFOrWinUI -->|"Modern"| WinUI["WinUI 3"]
アーキテクチャ決定フローチャート
flowchart TD
    Start["Service Design Decision"] --> Scale{"Expected scale?"}

    Scale -->|"Single team, moderate load"| Monolith["Modular Monolith"]
    Scale -->|"Multiple teams, high load"| Micro["Microservices"]

    Monolith --> MonoComm{"Communication pattern?"}
    MonoComm -->|"In-process"| MediatR["MediatR + Vertical Slices"]
    MonoComm -->|"Async events"| MonoBus["MassTransit (in-memory)"]

    Micro --> MicroComm{"Communication pattern?"}
    MicroComm -->|"Synchronous"| gRPC["gRPC / REST"]
    MicroComm -->|"Asynchronous"| MsgBus["Message Bus<br/>(RabbitMQ / Azure SB)"]
    MicroComm -->|"Both"| Hybrid["gRPC + Message Bus"]

    Micro --> DataStrategy{"Data strategy?"}
    DataStrategy -->|"Shared DB"| SharedDB["Shared Database<br/>(simpler, less isolation)"]
    DataStrategy -->|"DB per service"| OwnDB["Database per Service<br/>(more isolation, eventual consistency)"]

図をコードとして記述する際の規約

命名規約
  • ノード ID には PascalCase を使用します:OrderService、CustomerDB
  • 技術名を含む、説明的なラベルを使用します:API["Order API<br/>(ASP.NET Core)"]
  • 一貫した略語を使用します:DB(データベース)、API(エンドポイント)、SVC(サービス)、MQ(メッセージキュー)
  • サブグラフにはレイヤー名または階層名を接頭辞として付けます:subgraph DataTier["Data Tier"]
グループ化のパターン
  • アーキテクチャ層ごとにグループ化します(プレゼンテーション、アプリケーション、ドメイン、インフラストラクチャ)
  • デプロイ境界ごとにグループ化します(コンテナ、ポッド、VM)
  • マイクロサービス図では、チームの担当範囲ごとにグループ化します
  • 視覚的なグループ化にはサブグラフを使用します。読みやすさを保つため、ネストは2階層までにします
GitHub でのレンダリングのヒント
  • GitHub は、Markdown ファイル、イシュー、PR、ディスカッション内の mermaid 言語識別子を指定したフェンス付きコードブロックで Mermaid をレンダリングします
  • 推奨される図の最大サイズは、読みやすさを考慮して約50ノードです
  • GitHub はデフォルトでライトテーマを使用するため、白い背景で見えなくなる明るい色の塗りつぶしは避けてください
  • 図はコンテナーの幅に合わせて自動調整されるため、ノードラベルは簡潔にします(1行あたり30文字未満)
  • ノードラベル内の改行には <br/> を使用します(\n は使用しません)
  • マージ前に GitHub で図をテストしてください。構文エラーがあると、コードがテキストのまま表示されます
ダークモードに関する考慮事項
  • ダークモードで適切に表示されないハードコードされた色は避け、可能な場合は Mermaid のテーマ変数を使用してください
  • Mermaid のデフォルトの色は、GitHub のライトテーマとダークテーマの両方で機能します
  • カスタムの style ディレクティブを使用する場合は、GitHub のライトモードとダークモードの両方でテストしてください
  • 保守性を高めるため、インラインの style よりも意味に基づいた classDef スタイルを優先してください:
%%{init: {'theme': 'neutral'}}%%
graph LR
    A["Service A"] --> B["Service B"]
    A --> C["Service C"]

    classDef healthy fill:#4caf50,color:#fff
    classDef degraded fill:#ff9800,color:#fff
    class A healthy
    class B degraded
    class C healthy
  • neutral テーマは、GitHub でテーマをまたいだ互換性が最も高くなります
  • ドキュメントサイト(Starlight、Docusaurus)では、テーマはプラットフォームの CSS によって制御されます。Mermaid は自動的に継承します
図のサイズのガイドライン
図の種類推奨される最大ノード数備考
C4 コンテキスト10-121つのシステムと外部アクター
C4 コンテナ15-20内部コンテナとデータストア
C4 コンポーネント15-20単一サービスの内部構造
シーケンス参加者8人これ以上は読みにくくなります
クラスクラス10-15個複数の図に分割します
ERエンティティ10-12個境界づけられたコンテキストごとに分割します
状態状態12-15個複雑なワークフローは分割します
フローチャートノード15-20個意思決定ツリーは要点を絞ります

エージェントに関する注意点

  1. 図では常に .NET-specific content を使用してください -- 汎用的な図は生成しないでください。実際の .NET 型(DbContext、IRepository、MediatR)、実際の .NET ツール(EF Core、MassTransit、YARP)、実際の .NET パターン(ミドルウェアパイプライン、DI 登録)を使用してください。

  2. 図のノード数は 50 未満にしてください -- それより大きな図は GitHub やドキュメントサイトで適切に表示されません。複雑なアーキテクチャは、1 つの巨大な図にまとめるのではなく、複数の目的別の図(コンテキスト、コンテナー、コンポーネント)に分けてください。

  3. ノードラベルの改行には \n ではなく <br/> を使用してください -- Mermaid は \n を文字列としてそのまま表示します。複数行のラベルには <br/> の HTML タグが必要です。

  4. コミット前に Mermaid の構文をテストしてください -- 構文エラーがあると、GitHub では図ではなく生のテキストが表示されます。Mermaid Live Editor(https://mermaid.live)またはローカルのプレビュー用ツールで検証してください。

  5. ER 図のリレーションシップ表記には UML ではなく Mermaid の構文を使用してください -- 1 対多には ||--o{、1 対 1 には ||--|| を使用してください。UML の多重度表記は使用しないでください。

  6. GitHub との互換性を保つため、neutral テーマを使用してください -- %%{init: {'theme': 'neutral'}}%% はライトモードとダークモードの両方で最適な表示を実現します。

  7. シーケンス図の参加者名には特殊文字を使用できません -- スペースや特殊文字を含む名前には、participant DB as "SQL Server" のエイリアス構文を使用してください。

  8. 入れ子になったジェネリック型(Task~List~T~~)は、すべての Mermaid バージョンで表示されるとは限りません -- 入れ子になったジェネリック型の末尾にある二重の ~~ には Mermaid v10.3 以降が必要です。複雑なジェネリック型の図をコミットする前に、対象環境での表示をテストしてください。

  9. GitHub 向けの図では Font Awesome のアイコン構文(fa:fa-user)を使用しないでください -- GitHub のネイティブ Mermaid レンダラーは Font Awesome の CSS を読み込みません。アイコンは文字列としてそのまま表示されます。代わりにプレーンテキストのラベルを使用してください。

  10. ドキュメントプラットフォームで Mermaid のレンダリングを設定しないでください -- プラットフォームの設定(Starlight remark plugin、Docusaurus theme、DocFX template)は [skill:dotnet-documentation-strategy] に含まれます。このスキルが提供するのは図の内容のみです。

コメント