Classes/DrawClasses.ps1

#Requires -Version 5.1
# ============================================================
# DrawManagement — Core Classes
# All data models used throughout the module
#
# REVIEW CHANGES vs original:
# [CLASS-01] Removed [System.Collections.Generic.List[T]]::new()
# (C#-style constructor call) — replaced with New-Object
# 'System.Collections.Generic.List[T]' throughout.
# [CLASS-02] Hashtable field defaults (@{}) moved from field
# declarations into every constructor body. In PS 5.1,
# reference-type field defaults are evaluated once at class
# parse time and then shared across all instances — a
# classic aliasing bug that silently corrupts metadata.
# [CLASS-03] Removed ?? null-coalescing operator — PS 5.1 does not
# support it. Replaced with if/else expressions.
# [CLASS-04] [void]$sb.AppendLine() replaced with $null = $sb.…
# [void] cast works inside class methods but $null= is the
# standard PowerShell idiom and avoids confusion.
# [CLASS-05] All width/height/bool defaults moved into constructor
# bodies (same reason as CLASS-02).
# [CLASS-06] Added null/empty guards on every public method parameter
# so callers get an actionable error message, not a NullRef.
# [CLASS-07] DrawCell.ToXml: extracted BuildUserObjectAttrs() hidden
# helper — eliminates the duplicate attribute-building code
# that existed in the original plain-cell and UserObject
# branches.
# [CLASS-08] DrawCell.NewId: replaced .Substring(0,12) with a PS-
# style -replace + Substring(0,16) — safer and more
# readable than chained C# method calls.
# [CLASS-09] DrawPage.ToXml: added escape on page name so emoji and
# special characters do not produce malformed XML.
# [CLASS-10] DrawFile.ToXml: vars JSON escaping changed from a single
# blanket .Replace('"','"') to per-value escaping,
# which correctly handles values that already contain quotes.
# [CLASS-11] DrawStencil.ToLibraryEntry: added up-front validation so
# a partially constructed stencil fails loudly rather than
# silently emitting an empty/broken JSON entry.
# [CLASS-12] DrawStencil style-only XML: escaped the style string with
# -replace '"','"' before embedding in the XML string,
# because style values can contain double-quote characters.
# ============================================================

# ── Enums ────────────────────────────────────────────────────────────

enum DrawEdgeStyle {
    Orthogonal
    Straight
    Curved
    ElbowEdge
    EntityRelation
    IsometricEdge
}

enum DrawArrowType {
    Block
    Open
    Classic
    None
    Oval
    Diamond
    ERone
    ERmany
}

enum DrawShapeCategory {
    General
    Flowchart
    Network
    UML
    BPMN
    AWS
    Azure
    ActiveDirectory
    VMware
    Custom
}

enum DrawFontStyle {
    Normal    = 0
    Bold      = 1
    Italic    = 2
    Underline = 4
}

# ── DrawCell — base shape / vertex ───────────────────────────────────

class DrawCell {
    [string]    $Id
    [string]    $Label
    [string]    $Style
    [double]    $X
    [double]    $Y
    [double]    $Width
    [double]    $Height
    [string]    $ParentId
    [bool]      $IsVertex
    [bool]      $IsEdge
    [hashtable] $Metadata
    [string]    $Tooltip
    [string]    $Link
    # [FIX-16] draw.io substitutes %var% ONLY on a UserObject carrying
    # placeholders="1". It is a structural attribute, not user metadata, so
    # it needs its own home on the class — ConvertFrom-UserObjectAttr
    # deliberately keeps it out of the Metadata bag.
    [bool]      $Placeholders

    DrawCell() {
        $this.Id       = [DrawCell]::NewId()
        $this.ParentId = '1'
        $this.IsVertex = $true
        $this.IsEdge   = $false
        $this.Width    = 120
        $this.Height   = 60
        # [CLASS-02] per-instance hashtable — not a shared field default
        $this.Metadata = @{}
    }

    DrawCell([string]$label) {
        $this.Id       = [DrawCell]::NewId()
        $this.Label    = $label
        $this.ParentId = '1'
        $this.IsVertex = $true
        $this.IsEdge   = $false
        $this.Width    = 120
        $this.Height   = 60
        $this.Metadata = @{}
    }

    # [CLASS-08] PS-style new ID — no chained C# .Substring
    static [string] NewId() {
        $raw = [System.Guid]::NewGuid().ToString() -replace '-', ''
        return $raw.Substring(0, 16)
    }

    # [FIX-09] Escape a value destined for an XML attribute that draw.io
    # renders as TEXT (tooltips, UserObject metadata values).
    #
    # Two things go wrong with a plain SecurityElement::Escape here:
    #
    # 1. Authors write "
" meaning "line break". Escape() turns the
    # leading '&' into '&', so the file carries the literal seven
    # characters "
" and the reader sees them instead of a break.
    # 2. A real newline character cannot survive in an XML attribute at
    # all: XML 1.0 attribute-value normalisation (§3.3.3) replaces
    # #xA/#xD/#x9 with a space. Only a character reference preserves
    # one, which is precisely what "
" is for.
    #
    # So: fold the author's "
" convention into real newlines FIRST,
    # escape the metacharacters (which correctly turns a genuine '&' in
    # "R&D" into '&'), then re-emit newlines as character references.
    #
    # draw.io's tooltip renderer splits on the newline character — this is
    # how its own Edit Data tooltips put one property per line — so the
    # result renders as separate lines. HTML tags are NOT the mechanism
    # here: tooltip values are passed through htmlEntities and a literal
    # <br> would be displayed rather than obeyed. Labels are the opposite
    # case (HTML, html=1) and deliberately keep plain Escape().
    static [string] EscapeTextAttr([string]$text) {
        if ([string]::IsNullOrEmpty($text)) { return '' }

        # 1. author-written character references -> real newline
        $t = $text -replace '&#(?:10|[xX]0*[aA]);', "`n"
        # 2. normalise CRLF / CR -> LF
        $t = $t -replace "`r`n", "`n"
        $t = $t -replace "`r", "`n"
        # 3. escape XML metacharacters (leaves newlines untouched)
        $escaped = [DrawCell]::EscapeAttr($t)
        # 4. re-emit newlines as references so normalisation cannot eat them
        return ($escaped -replace "`n", '&#10;')
    }

    # [FIX-40] Escape ANY value written into an XML attribute. Escaping the
    # metacharacters is not enough: XML 1.0 forbids most C0 control
    # characters, U+FFFE/U+FFFF and unpaired surrogates outright — not even a
    # character reference may carry them — so one stray 0x01 in a label
    # (data pulled from an API, a pasted cell) produced a file that draw.io
    # refuses to open, with nothing reported at save time. They carry no
    # meaning in a diagram, so they are dropped.
    static [string] EscapeAttr([string]$text) {
        if ([string]::IsNullOrEmpty($text)) { return '' }
        $t = $text -replace '[\x00-\x08\x0B\x0C\x0E-\x1F\uFFFE\uFFFF]', ''
        $t = $t -replace '[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]', ''
        return [System.Security.SecurityElement]::Escape($t)
    }

    # [FIX-41] Map metadata/vars keys to XML attribute names that are valid
    # AND unique on the element. The old inline rule replaced unusual
    # characters with '_' and nothing else, which wrote unopenable files for
    # a key starting with a digit ('1st'), two keys that sanitise to the
    # same name ('a b' and 'a_b'), and a key equal to an attribute the
    # element already carries ('id', 'label', or 'tooltip' next to -Tooltip).
    #
    # A key that is already a legal attribute name is kept verbatim — that
    # includes dots and non-ASCII letters, which draw.io's Edit Data accepts,
    # so 'IP.Address' no longer comes back from a round-trip as 'IP_Address'
    # (breaking every %IP.Address% placeholder). Anything else is sanitised,
    # and a clash gets a numeric suffix. $taken lists names already in use.
    static [System.Collections.Specialized.OrderedDictionary] AttrNames(
            [System.Collections.IDictionary]$bag, [string[]]$taken) {
        $map  = [ordered]@{}
        $used = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::Ordinal)
        $null = $used.Add('xmlns')   # would rebind the element's namespace
        foreach ($t in $taken) { if ($t) { $null = $used.Add($t) } }

        foreach ($key in [DrawCell]::SortedKeys($bag)) {
            # [FIX-16] structural — emitted separately, never as a value
            if ($key -eq 'placeholders') { continue }
            $name = $key
            try { $null = [System.Xml.XmlConvert]::VerifyNCName($name) }
            catch {
                $name = $key -replace '[^a-zA-Z0-9_\-]', '_'
                if ($name -notmatch '^[A-Za-z_]') { $name = "_$name" }
            }
            if ($used.Contains($name)) {
                $n = 2
                while ($used.Contains("${name}_$n")) { $n++ }
                $name = "${name}_$n"
            }
            $null = $used.Add($name)
            $map[$key] = $name
        }
        return $map
    }

    # [FIX-37] Metadata and Vars are plain [hashtable]s, whose enumeration
    # order is an implementation detail of the hash buckets — not insertion
    # order, and not stable across runs or PowerShell versions. Writing them
    # in that order made two saves of the same diagram differ textually, so
    # every regenerated .drawio produced a diff with nothing actually changed.
    # Serialise keys in one fixed order instead. OrdinalIgnoreCase is a total
    # order here because a PowerShell hashtable's keys are already unique
    # case-insensitively, and it is culture-independent.
    static [string[]] SortedKeys([System.Collections.IDictionary]$bag) {
        if ($null -eq $bag -or $bag.Count -eq 0) { return [string[]]@() }
        [string[]]$keys = @($bag.Keys | ForEach-Object { [string]$_ })
        [System.Array]::Sort($keys, [System.StringComparer]::OrdinalIgnoreCase)
        return $keys
    }

    # [FIX-16] 'placeholders' is a structural attribute, not user metadata.
    # Callers used to set it through the Metadata bag (that is how it reached
    # the file before it had a field of its own), so keep accepting it from
    # there — but resolve it to a single boolean so it is emitted exactly
    # once, verbatim, and never routed through EscapeTextAttr.
    static [bool] WantsPlaceholders([bool]$flag, [hashtable]$metadata) {
        if ($flag) { return $true }
        if ($null -ne $metadata -and $metadata.ContainsKey('placeholders')) {
            $v = ([string]$metadata['placeholders']).Trim()
            return ($v -eq '1' -or $v -eq 'true')
        }
        return $false
    }

    # [CLASS-07] Hidden helper — single place that builds attribute fragments
    hidden [string] BuildUserObjectAttrs() {
        $parts = New-Object System.Collections.Generic.List[string]

        $hasTip  = -not [string]::IsNullOrWhiteSpace($this.Tooltip)
        $hasLink = -not [string]::IsNullOrWhiteSpace($this.Link)

        # [FIX-37] fixed order, [FIX-41] valid and unique attribute names
        $taken = @('id', 'label', $(if ($hasTip) { 'tooltip' }), $(if ($hasLink) { 'link' }))
        $names = [DrawCell]::AttrNames($this.Metadata, [string[]]$taken)
        foreach ($key in $names.Keys) {
            # [FIX-09] text-rendered value — see DrawCell::EscapeTextAttr
            $val  = [DrawCell]::EscapeTextAttr([string]$this.Metadata[$key])
            $null = $parts.Add(" $($names[$key])=`"${val}`"")
        }

        if ($hasTip) {
            $t    = [DrawCell]::EscapeTextAttr($this.Tooltip)
            $null = $parts.Add(" tooltip=`"$t`"")
        }

        if ($hasLink) {
            $lnk  = [DrawCell]::EscapeAttr($this.Link)
            $null = $parts.Add(" link=`"$lnk`"")
        }

        # [FIX-16] structural, not metadata — emit verbatim, never escaped
        if ([DrawCell]::WantsPlaceholders($this.Placeholders, $this.Metadata)) {
            $null = $parts.Add(" placeholders=`"1`"")
        }

        return ($parts -join '')
    }

    [string] ToXml() {
        # [CLASS-06] guard: ID is always set by constructor, but protect
        # against someone manually nulling it out
        if ([string]::IsNullOrWhiteSpace($this.Id)) {
            throw "DrawCell.ToXml: Id must not be null or empty."
        }
        # Default style rather than emitting an empty style attribute
        if ([string]::IsNullOrWhiteSpace($this.Style)) {
            $this.Style = 'rounded=0;whiteSpace=wrap;html=1;'
        }

        if ($this.Label) { $labelVal = $this.Label } else { $labelVal = '' }
        $safeLabel = [DrawCell]::EscapeAttr($labelVal)
        # [FIX-17] The style is author-supplied and legitimately contains '&'
        # (image= URLs with query strings). Unescaped it produces malformed
        # XML that draw.io cannot open at all.
        $safeStyle = [DrawCell]::EscapeAttr($this.Style)
        # [FIX-40] Ids are escaped like any other attribute. Ours are hex,
        # but Open-DrawFile keeps whatever id the source file used, and one
        # holding '&' or '"' was written back raw.
        $safeId     = [DrawCell]::EscapeAttr($this.Id)
        $safeParent = [DrawCell]::EscapeAttr($this.ParentId)

        $geom = "<mxGeometry x=`"$($this.X)`" y=`"$($this.Y)`" " +
                "width=`"$($this.Width)`" height=`"$($this.Height)`" as=`"geometry`"/>"

        $hasUserObj = ($this.Metadata.Count -gt 0) -or
                      (-not [string]::IsNullOrWhiteSpace($this.Tooltip)) -or
                      (-not [string]::IsNullOrWhiteSpace($this.Link)) -or
                      $this.Placeholders

        if ($hasUserObj) {
            # [FIX-36] The id goes on the WRAPPER ONLY, never on the inner
            # mxCell. draw.io's own encoder does the same — mxCellCodec's
            # afterEncode migrates the id outward and deletes it from the
            # inner node — and the decoder cannot tolerate both: mxCodec's
            # addElement throws '<id>: Duplicate ID' when two distinct
            # elements share one. The parent reference is then left null and
            # mxCodec.insertIntoGraph silently skips a cell whose parent is
            # null, so the cell never enters the model.
            #
            # Symptom: a wrapped container renders, but every child inside it
            # is INVISIBLE. Top-level cells are unaffected because parent="1"
            # (the layer) is already in the decoder's object table and never
            # reaches the id lookup. Confirmed against draw.io with a
            # two-cell A/B file differing only in this attribute.
            $attrs = $this.BuildUserObjectAttrs()
            $inner = "<mxCell style=`"$safeStyle`" " +
                     "vertex=`"1`" parent=`"$safeParent`">$geom</mxCell>"
            return "<UserObject label=`"$safeLabel`"$attrs id=`"$safeId`">$inner</UserObject>"
        }

        return "<mxCell id=`"$safeId`" value=`"$safeLabel`" style=`"$safeStyle`" " +
               "vertex=`"1`" parent=`"$safeParent`">$geom</mxCell>"
    }
}

# ── DrawEdge — connector between two cells ───────────────────────────

class DrawEdge {
    [string]    $Id
    [string]    $Label
    [string]    $SourceId
    [string]    $TargetId
    [string]    $Style
    [string]    $ParentId
    [string]    $Tooltip
    # [FIX-25] Edges take links exactly like vertices do — draw.io's
    # Graph.getLinkForCell makes no vertex/edge distinction, it just reads
    # cell.value.getAttribute('link'). Without a field here, a link on an
    # edge was read into nothing and silently lost on every round-trip:
    # ConvertFrom-UserObjectAttr deliberately keeps 'link' out of the
    # Metadata bag, so there was no fallback. Same data-loss class as FIX-16.
    [string]    $Link
    [hashtable] $Metadata
    # [FIX-16] see DrawCell.Placeholders — edge labels take %var% too
    [bool]      $Placeholders

    DrawEdge() {
        $this.Id       = [DrawCell]::NewId()
        $this.ParentId = '1'
        $this.Style    = 'edgeStyle=orthogonalEdgeStyle;html=1;'
        $this.Label    = ''
        # [CLASS-02] per-instance hashtable
        $this.Metadata = @{}
    }

    DrawEdge([string]$sourceId, [string]$targetId) {
        # [CLASS-06] validate inputs
        if ([string]::IsNullOrWhiteSpace($sourceId)) {
            throw "DrawEdge: sourceId must not be null or empty."
        }
        if ([string]::IsNullOrWhiteSpace($targetId)) {
            throw "DrawEdge: targetId must not be null or empty."
        }
        $this.Id       = [DrawCell]::NewId()
        $this.SourceId = $sourceId
        $this.TargetId = $targetId
        $this.ParentId = '1'
        $this.Style    = 'edgeStyle=orthogonalEdgeStyle;html=1;'
        $this.Label    = ''
        $this.Metadata = @{}
    }

    [string] ToXml() {
        if ([string]::IsNullOrWhiteSpace($this.Id)) {
            throw "DrawEdge.ToXml: Id must not be null or empty."
        }

        # [FIX-40] ids escaped — see DrawCell.ToXml
        if (-not [string]::IsNullOrWhiteSpace($this.SourceId)) {
            $srcAttr = " source=`"$([DrawCell]::EscapeAttr($this.SourceId))`""
        } else { $srcAttr = '' }

        if (-not [string]::IsNullOrWhiteSpace($this.TargetId)) {
            $tgtAttr = " target=`"$([DrawCell]::EscapeAttr($this.TargetId))`""
        } else { $tgtAttr = '' }

        if ($this.Label) { $labelVal = $this.Label } else { $labelVal = '' }
        $safeLabel = [DrawCell]::EscapeAttr($labelVal)
        # [FIX-17] see DrawCell.ToXml — the style must be escaped too
        $safeStyle  = [DrawCell]::EscapeAttr($this.Style)
        $safeId     = [DrawCell]::EscapeAttr($this.Id)
        $safeParent = [DrawCell]::EscapeAttr($this.ParentId)

        $geom = '<mxGeometry relative="1" as="geometry"/>'

        $wantsPh  = [DrawCell]::WantsPlaceholders($this.Placeholders, $this.Metadata)
        $hasTip   = -not [string]::IsNullOrWhiteSpace($this.Tooltip)
        $hasLink  = -not [string]::IsNullOrWhiteSpace($this.Link)

        # [FIX-25] A tooltip or a link REQUIRES the UserObject wrapper, and
        # must be written on the wrapper rather than on the inner mxCell.
        # draw.io resolves both from the cell's value object:
        # getTooltipForCell -> requires mxUtils.isNode(cell.value), reads
        # cell.value.attributes
        # getLinkForCell -> cell.value.getAttribute('link')
        # Neither ever looks at an attribute on the mxCell itself. The old
        # code put tooltip="" on the inner mxCell and did not count it towards
        # creating a wrapper at all, so an edge tooltip was written to the
        # file, survived round-trip, and NEVER rendered — silent, like the
        # rest of this defect family. DrawCell has always done this correctly;
        # only the edge path was wrong.
        if ($this.Metadata.Count -gt 0 -or $wantsPh -or $hasTip -or $hasLink) {
            $attrParts = New-Object System.Collections.Generic.List[string]
            # [FIX-37] fixed order, [FIX-41] valid and unique attribute names
            $taken = @('id', 'label', $(if ($hasTip) { 'tooltip' }), $(if ($hasLink) { 'link' }))
            $names = [DrawCell]::AttrNames($this.Metadata, [string[]]$taken)
            foreach ($key in $names.Keys) {
                # [FIX-09] text-rendered value — see DrawCell::EscapeTextAttr
                $val  = [DrawCell]::EscapeTextAttr([string]$this.Metadata[$key])
                $null = $attrParts.Add(" $($names[$key])=`"${val}`"")
            }
            if ($hasTip) {
                # [FIX-09] text-rendered value — see DrawCell::EscapeTextAttr
                $t    = [DrawCell]::EscapeTextAttr($this.Tooltip)
                $null = $attrParts.Add(" tooltip=`"$t`"")
            }
            if ($hasLink) {
                $lnk  = [DrawCell]::EscapeAttr($this.Link)
                $null = $attrParts.Add(" link=`"$lnk`"")
            }
            if ($wantsPh) { $null = $attrParts.Add(" placeholders=`"1`"") }
            $attrs = $attrParts -join ''

            # [FIX-36] see DrawCell.ToXml — the id belongs on the wrapper
            # only. An edge carries no children, so it cannot show the
            # invisible-child symptom itself, but a duplicate id anywhere in
            # the document makes mxCodec.addElement throw while it indexes
            # the whole file, which breaks unrelated cells.
            $inner = "<mxCell style=`"$safeStyle`" " +
                     "edge=`"1`"$srcAttr$tgtAttr parent=`"$safeParent`">" +
                     "$geom</mxCell>"
            return "<UserObject label=`"$safeLabel`"$attrs id=`"$safeId`">$inner</UserObject>"
        }

        return "<mxCell id=`"$safeId`" value=`"$safeLabel`" style=`"$safeStyle`" " +
               "edge=`"1`"$srcAttr$tgtAttr parent=`"$safeParent`">" +
               "$geom</mxCell>"
    }
}

# ── DrawPage — diagram tab / sheet ───────────────────────────────────

class DrawPage {
    [string] $Id
    [string] $Name
    [int]    $PageWidth
    [int]    $PageHeight
    [int]    $GridSize
    [bool]   $Grid
    [bool]   $Tooltips
    # [FIX-04] Canvas background colour (#RRGGBB). Empty or 'none' omits
    # the attribute entirely, which is draw.io's default white canvas.
    [string] $Background

    # [CLASS-01/02] Generic Lists — initialised in constructors
    [System.Collections.Generic.List[DrawCell]] $Cells
    [System.Collections.Generic.List[DrawEdge]] $Edges
    [System.Collections.Generic.List[DrawCell]] $Containers

    DrawPage() {
        $this.Id         = [DrawCell]::NewId()
        $this.Name       = 'Page-1'
        $this.PageWidth  = 1100
        $this.PageHeight = 850
        $this.GridSize   = 10
        $this.Grid       = $true
        $this.Tooltips   = $true
        $this.Background = ''
        $this.Cells      = New-Object 'System.Collections.Generic.List[DrawCell]'
        $this.Edges      = New-Object 'System.Collections.Generic.List[DrawEdge]'
        $this.Containers = New-Object 'System.Collections.Generic.List[DrawCell]'
    }

    DrawPage([string]$name) {
        if ([string]::IsNullOrWhiteSpace($name)) {
            throw "DrawPage: name must not be null or empty."
        }
        $this.Id         = [DrawCell]::NewId()
        $this.Name       = $name
        $this.PageWidth  = 1100
        $this.PageHeight = 850
        $this.GridSize   = 10
        $this.Grid       = $true
        $this.Tooltips   = $true
        $this.Background = ''
        $this.Cells      = New-Object 'System.Collections.Generic.List[DrawCell]'
        $this.Edges      = New-Object 'System.Collections.Generic.List[DrawEdge]'
        $this.Containers = New-Object 'System.Collections.Generic.List[DrawCell]'
    }

    [void] AddCell([DrawCell]$cell) {
        if ($null -eq $cell) { throw "DrawPage.AddCell: cell must not be null." }
        $this.Cells.Add($cell)
    }

    [void] AddEdge([DrawEdge]$edge) {
        if ($null -eq $edge) { throw "DrawPage.AddEdge: edge must not be null." }
        $this.Edges.Add($edge)
    }

    [void] AddContainer([DrawCell]$container) {
        if ($null -eq $container) { throw "DrawPage.AddContainer: container must not be null." }
        $this.Containers.Add($container)
    }

    [string] ToXml() {
        return $this.ToXml(@{})
    }

    # [FIX-39] File-level vars are written as attributes of the root cell
    # (id="0"). draw.io resolves %name% by walking from the cell up through
    # its ancestors to the root, reading each one's attributes — this is the
    # same place its own Edit Data on the diagram background stores them.
    # The old <mxfile vars="{...}"> attribute is never read by draw.io, so
    # every %var% rendered literally.
    [string] ToXml([hashtable]$vars) {
        if ([string]::IsNullOrWhiteSpace($this.Name)) {
            throw "DrawPage.ToXml: Name must not be null or empty."
        }

        if ($this.Tooltips) { $tooltipAttr = '1' } else { $tooltipAttr = '0' }
        if ($this.Grid)     { $gridAttr    = '1' } else { $gridAttr    = '0' }
        # [CLASS-09] escape the page name — emoji are fine, < > & are not
        $safeName    = [DrawCell]::EscapeAttr($this.Name)

        # [FIX-04] canvas background. Omit the attribute for empty/'none'
        # so draw.io falls back to its own default canvas.
        if ([string]::IsNullOrWhiteSpace($this.Background) -or
            $this.Background -eq 'none') {
            $bgAttr = ''
        }
        else {
            # Permissive on purpose: Add-DrawPage validates the format at the
            # input boundary, and Open-DrawFile must be able to round-trip
            # whatever draw.io actually wrote without failing the save.
            $safeBg = [DrawCell]::EscapeAttr($this.Background)
            $bgAttr = " background=`"$safeBg`""
        }

        # [CLASS-04] $null = instead of [void] cast
        $sb   = New-Object System.Text.StringBuilder
        $null = $sb.AppendLine("<diagram id=`"$([DrawCell]::EscapeAttr($this.Id))`" name=`"$safeName`">")
        $null = $sb.AppendLine(
            " <mxGraphModel dx=`"1200`" dy=`"800`" grid=`"$gridAttr`" " +
            "gridSize=`"$($this.GridSize)`" guides=`"1`" tooltips=`"$tooltipAttr`" " +
            "connect=`"1`" arrows=`"1`" fold=`"1`" page=`"1`" pageScale=`"1`" " +
            "pageWidth=`"$($this.PageWidth)`" pageHeight=`"$($this.PageHeight)`"$bgAttr " +
            "math=`"0`" shadow=`"0`">")
        $null = $sb.AppendLine(' <root>')
        if ($null -ne $vars -and $vars.Count -gt 0) {
            # 'id' and 'label' belong to the root cell itself and are draw.io
            # built-in placeholders anyway, so a var of that name is dropped.
            $own = @{}
            foreach ($k in $vars.Keys) { if ([string]$k -notin 'id', 'label') { $own[$k] = $vars[$k] } }
            $attrs = New-Object System.Text.StringBuilder
            # [FIX-41] valid and unique attribute names
            $names = [DrawCell]::AttrNames($own, [string[]]@('id', 'label'))
            foreach ($k in $names.Keys) {
                $val  = [DrawCell]::EscapeTextAttr([string]$own[$k])
                $null = $attrs.Append(" $($names[$k])=`"${val}`"")
            }
            $null = $sb.AppendLine(" <object label=`"`"$($attrs.ToString()) id=`"0`"><mxCell/></object>")
        }
        else {
            $null = $sb.AppendLine(' <mxCell id="0"/>')
        }
        $null = $sb.AppendLine(' <mxCell id="1" parent="0"/>')

        foreach ($c in $this.Containers) { $null = $sb.AppendLine(" $($c.ToXml())") }
        foreach ($c in $this.Cells)      { $null = $sb.AppendLine(" $($c.ToXml())") }
        foreach ($e in $this.Edges)      { $null = $sb.AppendLine(" $($e.ToXml())") }

        $null = $sb.AppendLine(' </root>')
        $null = $sb.AppendLine(' </mxGraphModel>')
        $null = $sb.AppendLine('</diagram>')
        return $sb.ToString()
    }
}

# ── DrawStencil — embedded custom shape (from VSSX / SVG / PNG) ──────

class DrawStencil {
    [string] $Name
    [string] $Style
    [int]    $Width
    [int]    $Height
    [string] $ImageData
    [string] $MxGraphXml
    [string] $Category
    [bool]   $AspectFixed

    DrawStencil([string]$name) {
        if ([string]::IsNullOrWhiteSpace($name)) {
            throw "DrawStencil: name must not be null or empty."
        }
        $this.Name        = $name
        $this.Width       = 80
        $this.Height      = 60
        $this.AspectFixed = $false
        $this.Category    = 'Custom'
    }

    [string] ToLibraryEntry() {
        # [CLASS-11] early validation
        if ([string]::IsNullOrWhiteSpace($this.Name)) {
            throw "DrawStencil.ToLibraryEntry: Name must not be empty."
        }
        if ($this.Width -le 0 -or $this.Height -le 0) {
            throw ("DrawStencil.ToLibraryEntry: Width and Height must be positive " +
                   "on stencil '$($this.Name)'. Got $($this.Width)x$($this.Height).")
        }
        if ([string]::IsNullOrWhiteSpace($this.ImageData) -and
            [string]::IsNullOrWhiteSpace($this.MxGraphXml) -and
            [string]::IsNullOrWhiteSpace($this.Style)) {
            throw ("DrawStencil.ToLibraryEntry: one of ImageData, MxGraphXml or Style " +
                   "must be set on stencil '$($this.Name)'.")
        }

        $entry = [ordered]@{
            title = $this.Name
            w     = $this.Width
            h     = $this.Height
        }

        if ($this.AspectFixed) { $entry['aspect'] = 'fixed' }

        if (-not [string]::IsNullOrWhiteSpace($this.ImageData)) {
            $entry['data'] = $this.ImageData
        }
        elseif (-not [string]::IsNullOrWhiteSpace($this.MxGraphXml)) {
            $entry['xml'] = $this.MxGraphXml
        }
        else {
            # [CLASS-12] escape style value so embedded double-quotes
            # do not break the surrounding XML attribute string
            # [FIX-22] ...and '&' too. A style legitimately carries one in an
            # image= URL query string ('?a=1&b=2'), and with only the quote
            # replaced this element text was not parseable XML. draw.io runs
            # mxUtils.parseXml() over this payload when it loads a library, so
            # the stencil silently failed to appear. The enclosing .drawio file
            # still parsed, which is why this hid: the mxlibrary sidecar lives
            # inside an XML COMMENT, and comment content is never parsed.
            $escapedStyle = [DrawCell]::EscapeAttr($this.Style)
            $xml = ('<mxGraphModel><root>' +
                    '<mxCell id="0"/><mxCell id="1" parent="0"/>' +
                    "<mxCell id=`"2`" value=`"`" style=`"$escapedStyle`" " +
                    "vertex=`"1`" parent=`"1`">" +
                    "<mxGeometry width=`"$($this.Width)`" height=`"$($this.Height)`" " +
                    'as="geometry"/>' +
                    '</mxCell></root></mxGraphModel>')
            $entry['xml'] = $xml
        }

        return ($entry | ConvertTo-Json -Compress -Depth 3)
    }
}

# ── DrawFile — top-level .drawio document ────────────────────────────

class DrawFile {
    [string]    $FilePath
    [string]    $Host
    [string]    $Version
    [hashtable] $Vars

    [System.Collections.Generic.List[DrawPage]]    $Pages
    [System.Collections.Generic.List[DrawStencil]] $EmbeddedStencils

    DrawFile() {
        $this.Host             = 'app.diagrams.net'
        $this.Version          = '21.0.0'
        $this.Vars             = @{}
        $this.Pages            = New-Object 'System.Collections.Generic.List[DrawPage]'
        $this.EmbeddedStencils = New-Object 'System.Collections.Generic.List[DrawStencil]'
    }

    DrawFile([string]$filePath) {
        if ([string]::IsNullOrWhiteSpace($filePath)) {
            throw "DrawFile: filePath must not be null or empty."
        }
        $this.FilePath         = $filePath
        $this.Host             = 'app.diagrams.net'
        $this.Version          = '21.0.0'
        $this.Vars             = @{}
        $this.Pages            = New-Object 'System.Collections.Generic.List[DrawPage]'
        $this.EmbeddedStencils = New-Object 'System.Collections.Generic.List[DrawStencil]'
    }

    [void] AddPage([DrawPage]$page) {
        if ($null -eq $page) { throw "DrawFile.AddPage: page must not be null." }
        $this.Pages.Add($page)
    }

    [void] AddStencil([DrawStencil]$stencil) {
        if ($null -eq $stencil) { throw "DrawFile.AddStencil: stencil must not be null." }
        $this.EmbeddedStencils.Add($stencil)
    }

    [string] ToXml() {
        if ($this.Pages.Count -eq 0) {
            Write-Warning 'DrawFile.ToXml: no pages added — file will open blank in draw.io.'
        }

        # [FIX-23] Real UTC. 'Z' is not a .NET format specifier, so it was
        # emitted as a literal suffix on a LOCAL time — the file claimed
        # 12:18:32Z while UTC was 10:18:32Z. Identical to the bug already
        # fixed in Build/Update-DrawShapeIndex.ps1's 'generated' stamp.
        $modified = [datetime]::UtcNow.ToString('yyyy-MM-ddTHH:mm:ss.fffZ')

        # [FIX-39] Vars are emitted on every page's root cell — see
        # DrawPage.ToXml([hashtable]). The former <mxfile vars="{...}">
        # attribute was never read by draw.io (and is dropped on its next
        # save), so it is no longer written; Open-DrawFile still reads it
        # from older files. Keys are sorted ([FIX-37]) and values go through
        # EscapeTextAttr, so 'R&D <Dept>' survives as text ([FIX-22]).
        $sb   = New-Object System.Text.StringBuilder
        $null = $sb.AppendLine('<?xml version="1.0" encoding="UTF-8"?>')
        $null = $sb.AppendLine(
            "<mxfile host=`"$([DrawCell]::EscapeAttr($this.Host))`" modified=`"$modified`" " +
            "agent=`"DrawManagement-PS`" version=`"$([DrawCell]::EscapeAttr($this.Version))`" " +
            "type=`"device`">")

        foreach ($p in $this.Pages) {
            $null = $sb.Append($p.ToXml($this.Vars))
        }

        if ($this.EmbeddedStencils.Count -gt 0) {
            $entries = ($this.EmbeddedStencils |
                        ForEach-Object { $_.ToLibraryEntry() }) -join ','

            # [FIX-15] This comment is DrawManagement's own sidecar so that
            # Open-DrawFile can restore stencils; draw.io ignores XML
            # comments and loads palettes only from separate <mxlibrary>
            # files (see Export-DrawStencilLibrary).
            #
            # XML forbids '--' inside a comment, so a stencil title or style
            # containing a double hyphen would make the whole FILE
            # unparseable. Rewrite the second hyphen as the JSON escape
            # -: still valid JSON, decodes back to '--' on read, and
            # cannot terminate the comment.
            $backslash   = [char]0x5C
            $safeEntries = $entries -replace '--', ('-' + $backslash + 'u002D')
            $null = $sb.AppendLine("<!-- mxlibrary:[$safeEntries] -->")
        }

        $null = $sb.AppendLine('</mxfile>')
        return $sb.ToString()
    }

    [void] Save() {
        if ([string]::IsNullOrWhiteSpace($this.FilePath)) {
            throw "DrawFile.Save: FilePath is not set. Call Save(path) or set FilePath first."
        }
        $xml = $this.ToXml()
        [System.IO.File]::WriteAllText(
            $this.FilePath, $xml, [System.Text.Encoding]::UTF8)
    }

    [void] Save([string]$path) {
        if ([string]::IsNullOrWhiteSpace($path)) {
            throw "DrawFile.Save: path must not be null or empty."
        }
        $this.FilePath = $path
        $this.Save()
    }
}