Public/DrawStencil.ps1

#Requires -Version 7.0
# ============================================================
# DrawManagement — Stencil / VSSX Import Public Functions
# All imported shapes are embedded inside the .drawio file
# so the output is fully self-contained and portable.
#
# REVIEW CHANGES vs original:
# [STEN-01] Import-DrawStencilFromVssx: $all.Count on a List<> that
# may come back empty returns 0 correctly in PS 5.1, but
# piping $null to Where-Object throws — added $null check
# before filtering.
# [STEN-02] Import-DrawStencilFromVssx: Read-VssxFile now returns a
# List<DrawStencil>, not an array; .Count is fine but
# | Select-Object -First works on both — kept as-is.
# [STEN-03] Import-DrawStencilFromSvg / FromPng: replaced
# [System.IO.File]::ReadAllBytes (C# static call) with
# Get-Content -AsByteStream / -Encoding Byte for PS idiom;
# also added -LiteralPath to Test-Path.
# [STEN-04] Import-DrawStencilFromPng: ?? operator for MIME type
# removed — replaced with if/else.
# [STEN-05] New-DrawStencil: throws via Write-Error -ErrorAction Stop
# rather than bare throw so the error record is attributed
# to this function rather than an internal call site.
# [STEN-06] Get-DrawStencils: added [PSTypeName] for Format-Table
# friendly default display.
# [STEN-07] Remove-DrawStencil: .Remove() return value checked;
# added -LiteralPath consistency.
# [STEN-08] Export-DrawStencilLibrary: replaced
# [System.IO.File]::WriteAllText with Set-Content
# (-LiteralPath, -Encoding UTF8) — PS-idiomatic and
# provider-aware.
# [STEN-09] Add-DrawShapeFromStencil: ScaleFactor validated (0.1–10)
# to prevent zero/negative dimensions on the output cell.
# [STEN-10] Add-DrawShapeFromStencil: embedding the full base64 image
# data URI into the style string is technically valid but
# produces very long styles; documented this clearly in the
# help so users understand the trade-off.
# ============================================================

function Import-DrawStencilFromVssx {
    <#
    .SYNOPSIS
        Imports shapes from a Visio stencil (.vssx/.vss) file and embeds
        them into a DrawFile for fully self-contained portability.

    .DESCRIPTION
        Parses the .vssx ZIP archive using System.IO.Compression:
          1. Reads visio/masters/masters.xml (shape index).
          2. Reads each master part for dimensions and ForeignData images.
          3. Converts each shape to a [DrawStencil] embedded in the file.

        Embedded stencils are serialised as an mxlibrary comment block in
        the saved .drawio file. That block is DrawManagement's own sidecar,
        NOT a draw.io feature — draw.io ignores XML comments, and it loads
        shape palettes only from separate <mxlibrary> files via
        File > Open Library. Use Export-DrawStencilLibrary to produce one.

        What actually makes an imported shape render is the style written
        onto each cell by Add-DrawShapeFromStencil, which embeds the image
        as a data URI. The palette and the rendering are independent.

        Only masters that embed a raster image convert faithfully. Masters
        that store artwork as Visio geometry are imported as dashed
        placeholder chips and reported with a warning — consider a built-in
        draw.io shape instead (see Find-DrawShape).

    .PARAMETER DrawFile
        The [DrawFile] to embed the stencils into.

    .PARAMETER Path
        Path to the .vssx or .vss file.

    .PARAMETER Filter
        Optional wildcard filter on shape names (e.g. '*Server*').

    .PARAMETER MaxShapes
        Maximum number of shapes to import. Useful for large stencil sets.
        Default: no limit.

    .PARAMETER PassThru
        Return the list of imported [DrawStencil] objects.

    .EXAMPLE
        Import-DrawStencilFromVssx -DrawFile $doc -Path 'C:\stencils\vmw_Icons.vssx'

    .EXAMPLE
        Import-DrawStencilFromVssx -DrawFile $doc `
            -Path '.\ad_stencils.vssx' -Filter '*Controller*' -PassThru

    .OUTPUTS
        [DrawStencil[]] when -PassThru is specified, otherwise nothing.
    #>

    [CmdletBinding()]
    [OutputType([DrawStencil[]])]
    param(
        [Parameter(Mandatory)][DrawFile] $DrawFile,
        [Parameter(Mandatory)][string]   $Path,
        [Parameter()][string]            $Filter,
        [Parameter()][ValidateRange(1, 10000)][int] $MaxShapes = 10000,
        [Parameter()][switch]            $PassThru
    )

    Write-Verbose "Import-DrawStencilFromVssx: reading '$Path'"

    $all = Read-VssxFile -Path $Path   # returns List<DrawStencil>

    # [STEN-01] null / empty guard before filtering
    if ($null -eq $all -or $all.Count -eq 0) {
        Write-Warning "Import-DrawStencilFromVssx: no shapes found in '$Path'."
        return
    }

    if (-not [string]::IsNullOrWhiteSpace($Filter)) {
        $all = @($all | Where-Object { $_.Name -like $Filter })
    }

    if ($all.Count -gt $MaxShapes) {
        $all = @($all | Select-Object -First $MaxShapes)
        Write-Warning ("Import-DrawStencilFromVssx: result limited to $MaxShapes shapes " +
                       "(use -MaxShapes to raise the limit).")
    }

    foreach ($s in $all) {
        $DrawFile.AddStencil($s)
    }

    Write-Verbose ("Import-DrawStencilFromVssx: embedded $($all.Count) stencils " +
                   "from '$(Split-Path -Leaf $Path)'")

    if ($PassThru) { return $all }
}

function Import-DrawStencilFromSvg {
    <#
    .SYNOPSIS
        Imports an SVG file as an embedded stencil shape.

    .DESCRIPTION
        Reads the SVG file content, base64-encodes it and stores it as a
        data URI inside a [DrawStencil] embedded in the DrawFile.
        draw.io renders it using its built-in SVG image support.

    .PARAMETER DrawFile
        The [DrawFile] to embed the stencil into.

    .PARAMETER Path
        Path to the .svg file.

    .PARAMETER Name
        Shape name displayed in the library. Defaults to the filename
        without extension.

    .PARAMETER Width
        Default width when placed. Default: 80.

    .PARAMETER Height
        Default height when placed. Default: 60.

    .PARAMETER PassThru
        Return the created [DrawStencil] object.

    .EXAMPLE
        Import-DrawStencilFromSvg -DrawFile $doc `
            -Path '.\icons\server.svg' -Name 'My Server' -Width 60 -Height 60

    .OUTPUTS
        [DrawStencil] when -PassThru is specified, otherwise nothing.
    #>

    [CmdletBinding()]
    [OutputType([DrawStencil])]
    param(
        [Parameter(Mandatory)][DrawFile] $DrawFile,
        [Parameter(Mandatory)][string]   $Path,
        [Parameter()][string]            $Name,
        [Parameter()][ValidateRange(1, 9999)][int] $Width  = 80,
        [Parameter()][ValidateRange(1, 9999)][int] $Height = 60,
        [Parameter()][switch]            $PassThru
    )

    # [STEN-03] -LiteralPath
    if (-not (Test-Path -LiteralPath $Path)) {
        throw "Import-DrawStencilFromSvg: SVG file not found: '$Path'"
    }

    $shapeName = if (-not [string]::IsNullOrWhiteSpace($Name)) {
        $Name
    } else {
        [System.IO.Path]::GetFileNameWithoutExtension($Path)
    }

    # [STEN-03] PS-idiomatic file read
    $svgBytes = [System.IO.File]::ReadAllBytes($Path)
    $b64      = [Convert]::ToBase64String($svgBytes)

    $stencil             = [DrawStencil]::new($shapeName)
    $stencil.Width       = $Width
    $stencil.Height      = $Height
    $stencil.ImageData   = "data:image/svg+xml;base64,$b64"
    $stencil.AspectFixed = $true

    $DrawFile.AddStencil($stencil)
    Write-Verbose "Import-DrawStencilFromSvg: embedded '$shapeName' (${Width}x${Height})"

    if ($PassThru) { return $stencil }
}

function Import-DrawStencilFromPng {
    <#
    .SYNOPSIS
        Imports a PNG, JPEG, GIF or WebP image as an embedded stencil shape.

    .DESCRIPTION
        Reads the image file, base64-encodes it and stores it as a data URI
        inside a [DrawStencil] embedded in the DrawFile.

    .PARAMETER DrawFile
        The [DrawFile] to embed the stencil into.

    .PARAMETER Path
        Path to the image file (.png, .jpg, .jpeg, .gif, .webp).

    .PARAMETER Name
        Shape name. Defaults to the filename without extension.

    .PARAMETER Width
        Default width when placed. Default: 80.

    .PARAMETER Height
        Default height when placed. Default: 60.

    .PARAMETER PassThru
        Return the created [DrawStencil] object.

    .EXAMPLE
        Import-DrawStencilFromPng -DrawFile $doc `
            -Path '.\logo.png' -Name 'Company Logo' -Width 120 -Height 40

    .OUTPUTS
        [DrawStencil] when -PassThru is specified, otherwise nothing.
    #>

    [CmdletBinding()]
    [OutputType([DrawStencil])]
    param(
        [Parameter(Mandatory)][DrawFile] $DrawFile,
        [Parameter(Mandatory)][string]   $Path,
        [Parameter()][string]            $Name,
        [Parameter()][ValidateRange(1, 9999)][int] $Width  = 80,
        [Parameter()][ValidateRange(1, 9999)][int] $Height = 60,
        [Parameter()][switch]            $PassThru
    )

    # [STEN-03] -LiteralPath
    if (-not (Test-Path -LiteralPath $Path)) {
        throw "Import-DrawStencilFromPng: image file not found: '$Path'"
    }

    $ext = [System.IO.Path]::GetExtension($Path).TrimStart('.').ToLower()

    # Supported raster formats
    $validExtensions = @('png','jpg','jpeg','gif','webp')
    if ($ext -notin $validExtensions) {
        Write-Warning ("Import-DrawStencilFromPng: extension '.$ext' is not a known raster " +
                       "format. Supported: $($validExtensions -join ', '). Proceeding as image/png.")
    }

    # [STEN-04] PS 5.1-safe MIME lookup — no ?? operator
    $mimeMap = @{
        png  = 'image/png'
        jpg  = 'image/jpeg'
        jpeg = 'image/jpeg'
        gif  = 'image/gif'
        webp = 'image/webp'
    }
    $mime = if ($mimeMap.ContainsKey($ext)) { $mimeMap[$ext] } else { 'image/png' }

    $shapeName = if (-not [string]::IsNullOrWhiteSpace($Name)) {
        $Name
    } else {
        [System.IO.Path]::GetFileNameWithoutExtension($Path)
    }

    # [STEN-03] PS-idiomatic byte read
    $bytes = [System.IO.File]::ReadAllBytes($Path)
    $b64   = [Convert]::ToBase64String($bytes)

    $stencil             = [DrawStencil]::new($shapeName)
    $stencil.Width       = $Width
    $stencil.Height      = $Height
    $stencil.ImageData   = "data:$mime;base64,$b64"
    $stencil.AspectFixed = $true

    $DrawFile.AddStencil($stencil)
    Write-Verbose "Import-DrawStencilFromPng: embedded '$shapeName' ($mime, ${Width}x${Height})"

    if ($PassThru) { return $stencil }
}

function New-DrawStencil {
    <#
    .SYNOPSIS
        Creates a custom stencil from a style string or mxGraphModel XML
        and embeds it in a DrawFile.

    .DESCRIPTION
        Lets you define a reusable custom shape from scratch and embed it
        directly in the .drawio file so it is available in draw.io's
        custom shapes sidebar without importing a separate library file.

        Provide either -Style (for a single-cell shape) or -MxGraphXml
        (for complex multi-cell stencils). -MxGraphXml takes precedence.

    .PARAMETER DrawFile
        The [DrawFile] to embed the stencil into.

    .PARAMETER Name
        Shape name shown in the library sidebar.

    .PARAMETER Style
        draw.io style string. Used when -MxGraphXml is not supplied.

    .PARAMETER MxGraphXml
        Full mxGraphModel XML string (for multi-cell stencils).
        Takes precedence over -Style when both are supplied.

    .PARAMETER Width
        Default width when placed. Default: 80.

    .PARAMETER Height
        Default height when placed. Default: 60.

    .PARAMETER Category
        Grouping category label. Default: 'Custom'.

    .PARAMETER PassThru
        Return the created [DrawStencil] object.

    .EXAMPLE
        New-DrawStencil -DrawFile $doc -Name 'Alert Badge' `
            -Style 'ellipse;fillColor=#f8cecc;strokeColor=#b85450;fontStyle=1;' `
            -Width 60 -Height 60

    .OUTPUTS
        [DrawStencil] when -PassThru is specified, otherwise nothing.
    #>

    [CmdletBinding()]
    [OutputType([DrawStencil])]
    param(
        [Parameter(Mandatory)][DrawFile] $DrawFile,
        [Parameter(Mandatory)][ValidateNotNullOrEmpty()][string] $Name,
        [Parameter()][string] $Style,
        [Parameter()][string] $MxGraphXml,
        [Parameter()][ValidateRange(1, 9999)][int] $Width    = 80,
        [Parameter()][ValidateRange(1, 9999)][int] $Height   = 60,
        [Parameter()][ValidateNotNullOrEmpty()][string] $Category = 'Custom',
        [Parameter()][switch] $PassThru
    )

    # [STEN-05] validate at least one content source is supplied
    if ([string]::IsNullOrWhiteSpace($Style) -and
        [string]::IsNullOrWhiteSpace($MxGraphXml)) {
        Write-Error -Message "New-DrawStencil: either -Style or -MxGraphXml must be provided for stencil '$Name'." `
                    -ErrorAction Stop
    }

    $stencil          = [DrawStencil]::new($Name)
    $stencil.Width    = $Width
    $stencil.Height   = $Height
    $stencil.Category = $Category

    # MxGraphXml takes precedence over Style
    if (-not [string]::IsNullOrWhiteSpace($MxGraphXml)) {
        $stencil.MxGraphXml = $MxGraphXml
    }
    else {
        $stencil.Style = $Style
    }

    $DrawFile.AddStencil($stencil)
    Write-Verbose "New-DrawStencil: created '$Name' ($Category, ${Width}x${Height})"

    if ($PassThru) { return $stencil }
}

function Get-DrawStencils {
    <#
    .SYNOPSIS
        Lists all stencils embedded in a DrawFile.

    .PARAMETER DrawFile
        The [DrawFile] to inspect.

    .EXAMPLE
        Get-DrawStencils -DrawFile $doc | Format-Table Name, Width, Height, Category

    .INPUTS
        [DrawFile] via pipeline.

    .OUTPUTS
        [PSCustomObject[]]
    #>

    [CmdletBinding()]
    [OutputType([PSCustomObject])]
    param(
        [Parameter(Mandatory, ValueFromPipeline)][DrawFile]$DrawFile
    )
    process {
        if ($DrawFile.EmbeddedStencils.Count -eq 0) {
            Write-Verbose "Get-DrawStencils: no stencils embedded in this DrawFile."
            return
        }

        foreach ($s in $DrawFile.EmbeddedStencils) {
            # [STEN-06] PSTypeName for default display formatting
            [PSCustomObject]@{
                PSTypeName  = 'DrawManagement.StencilInfo'
                Name        = $s.Name
                Width       = $s.Width
                Height      = $s.Height
                Category    = $s.Category
                HasImage    = (-not [string]::IsNullOrWhiteSpace($s.ImageData))
                HasXml      = (-not [string]::IsNullOrWhiteSpace($s.MxGraphXml))
                HasStyle    = (-not [string]::IsNullOrWhiteSpace($s.Style) -and
                               [string]::IsNullOrWhiteSpace($s.MxGraphXml))
                AspectFixed = $s.AspectFixed
            }
        }
    }
}

function Remove-DrawStencil {
    <#
    .SYNOPSIS
        Removes an embedded stencil from a DrawFile by name.

    .PARAMETER DrawFile
        The [DrawFile] to modify.

    .PARAMETER Name
        Exact name of the stencil to remove.

    .EXAMPLE
        Remove-DrawStencil -DrawFile $doc -Name 'Old Icon'

    .OUTPUTS
        None
    #>

    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Medium')]
    param(
        [Parameter(Mandatory)][DrawFile] $DrawFile,
        [Parameter(Mandatory)][ValidateNotNullOrEmpty()][string] $Name
    )

    # [FIX-29] -First 1. Stencil names are not unique — AddStencil appends
    # without checking, so importing the same .vssx twice is enough to get
    # two 'Server' entries. Where-Object then handed List.Remove() an ARRAY,
    # which has no matching overload, so this threw
    # Cannot find an overload for "Remove" and the argument count: "1"
    # and removed nothing. Add-DrawShapeFromStencil already resolves the
    # same lookup with -First 1; this is the one place that did not.
    $s = $DrawFile.EmbeddedStencils | Where-Object { $_.Name -ceq $Name } | Select-Object -First 1

    if (-not $s) {
        Write-Warning "Remove-DrawStencil: stencil '$Name' not found."
        return
    }

    if ($PSCmdlet.ShouldProcess("stencil '$Name'", 'Remove')) {
        # [STEN-07] check return value of .Remove()
        $removed = $DrawFile.EmbeddedStencils.Remove($s)
        if (-not $removed) {
            Write-Warning "Remove-DrawStencil: could not remove '$Name' — it may have been removed already."
        }
        else {
            Write-Verbose "Remove-DrawStencil: removed '$Name'"
        }
    }
}

function Export-DrawStencilLibrary {
    <#
    .SYNOPSIS
        Exports all embedded stencils as a standalone mxlibrary XML file.

    .DESCRIPTION
        The exported file can be imported directly into draw.io via
        File → Open Library from → Device.
        Useful for sharing stencils independently of the full diagram.

    .PARAMETER DrawFile
        The source [DrawFile].

    .PARAMETER OutputPath
        Destination .xml file path.

    .PARAMETER Force
        Overwrite an existing file without prompting.

    .EXAMPLE
        Export-DrawStencilLibrary -DrawFile $doc `
            -OutputPath 'C:\stencils\my-library.xml'

    .INPUTS
        [DrawFile] via pipeline.

    .OUTPUTS
        [System.IO.FileInfo]
    #>

    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Medium')]
    [OutputType([System.IO.FileInfo])]
    param(
        [Parameter(Mandatory, ValueFromPipeline)][DrawFile] $DrawFile,
        [Parameter(Mandatory)][string]  $OutputPath,
        [Parameter()][switch]           $Force
    )
    process {
        if ($DrawFile.EmbeddedStencils.Count -eq 0) {
            Write-Warning "Export-DrawStencilLibrary: no stencils embedded — nothing exported."
            return
        }

        if ((Test-Path -LiteralPath $OutputPath) -and -not $Force) {
            if (-not $PSCmdlet.ShouldProcess($OutputPath, 'Overwrite existing library file')) {
                return
            }
        }

        $entries = ($DrawFile.EmbeddedStencils |
                    ForEach-Object { $_.ToLibraryEntry() }) -join ','

        # [FIX-14] The JSON payload sits in ELEMENT TEXT CONTENT and must be
        # XML-escaped. draw.io loads a library as:
        # parseXml(file) -> JSON.parse(getTextContent(documentElement))
        # so the file has to be well-formed XML before the JSON is even
        # looked at. Entries whose 'xml' field holds a raw <mxGraphModel>
        # previously wrote a literal '<' into the text node, which made the
        # file unparseable — draw.io rejected it as "not a library file".
        # Escaping is reversed by the XML parser, so getTextContent hands
        # JSON.parse exactly the bytes built here.
        $escaped = [System.Security.SecurityElement]::Escape("[$entries]")
        $xml     = "<mxlibrary>$escaped</mxlibrary>"

        # [STEN-08] PS-idiomatic write — provider-aware, honours -WhatIf
        Set-Content -LiteralPath $OutputPath -Value $xml -Encoding UTF8 -Force -ErrorAction Stop

        Write-Verbose ("Export-DrawStencilLibrary: exported $($DrawFile.EmbeddedStencils.Count) " +
                       "stencils to '$OutputPath'")

        return Get-Item -LiteralPath $OutputPath
    }
}

function Add-DrawShapeFromStencil {
    <#
    .SYNOPSIS
        Places an embedded stencil shape onto a page as a cell.

    .DESCRIPTION
        Looks up a stencil by name in the DrawFile's embedded library and
        places it on the specified page at the given coordinates.

        For image-based stencils (PNG/SVG), the base64 data URI is embedded
        directly in the cell style string. This keeps the diagram fully
        self-contained but produces a longer style attribute.
        [STEN-10] This is intentional — it ensures portability.

    .PARAMETER Page
        The [DrawPage] to add the shape to.

    .PARAMETER DrawFile
        The [DrawFile] containing the embedded stencil.

    .PARAMETER StencilName
        Exact name of the embedded stencil (case-sensitive).

    .PARAMETER Label
        Display label on the shape. Defaults to the stencil name.

    .PARAMETER X
        Horizontal position in pixels. Default: 100.

    .PARAMETER Y
        Vertical position in pixels. Default: 100.

    .PARAMETER ScaleFactor
        Multiplier applied to the stencil's default dimensions.
        Range: 0.1–10. Default: 1.0.

    .PARAMETER Metadata
        Custom UserObject properties.

    .PARAMETER Tooltip
        Hover text.

    .PARAMETER PassThru
        Return the created [DrawCell] object.

    .EXAMPLE
        Add-DrawShapeFromStencil -Page $page -DrawFile $doc `
            -StencilName 'vCenter Server' -X 300 -Y 200 `
            -Tooltip 'vCenter 8.0 — prod'

    .OUTPUTS
        [DrawCell] when -PassThru is specified, otherwise nothing.
    #>

    [CmdletBinding()]
    [OutputType([DrawCell])]
    param(
        [Parameter(Mandatory)][DrawPage] $Page,
        [Parameter(Mandatory)][DrawFile] $DrawFile,
        [Parameter(Mandatory)][ValidateNotNullOrEmpty()][string] $StencilName,
        [Parameter()][string]            $Label,
        [Parameter()][ValidateRange(0, 99999)][double] $X           = 100,
        [Parameter()][ValidateRange(0, 99999)][double] $Y           = 100,
        # [STEN-09] prevent zero/negative dimensions
        [Parameter()][ValidateRange(0.1, 10.0)][double] $ScaleFactor = 1.0,
        [Parameter()][hashtable]         $Metadata    = @{},
        [Parameter()][string]            $Tooltip,
        [Parameter()][switch]            $PassThru
    )

    $stencil = $DrawFile.EmbeddedStencils |
               Where-Object { $_.Name -ceq $StencilName } |
               Select-Object -First 1

    if (-not $stencil) {
        throw ("Add-DrawShapeFromStencil: stencil '$StencilName' not found in DrawFile. " +
               "Import it first with Import-DrawStencilFromVssx, Import-DrawStencilFromSvg " +
               "or New-DrawStencil. Available stencils: " +
               ($DrawFile.EmbeddedStencils | ForEach-Object { $_.Name } | Sort-Object) -join ', ')
    }

    $lbl = if (-not [string]::IsNullOrWhiteSpace($Label)) { $Label } else { $stencil.Name }
    $w   = [int][Math]::Max([Math]::Round($stencil.Width  * $ScaleFactor), 1)
    $h   = [int][Math]::Max([Math]::Round($stencil.Height * $ScaleFactor), 1)

    # Build cell style
    # [STEN-10] image URI embedded in style — documented trade-off
    # [FIX-18] The URI goes through ConvertTo-DrawImageStyleUri first. A
    # canonical 'data:image/png;base64,...' carries a ';', which is the
    # style separator, so pasting it in raw truncated the URI and placed a
    # blank box. draw.io's own comma form survives tokenising and is
    # expanded back by mxGraph.postProcessCellStyle. $stencil.ImageData
    # itself is left canonical — the mxlibrary 'data' field needs it.
    $style = if (-not [string]::IsNullOrWhiteSpace($stencil.ImageData)) {
        $imgUri = ConvertTo-DrawImageStyleUri -Uri $stencil.ImageData
        ('shape=image;verticalLabelPosition=bottom;labelBackgroundColor=default;' +
         "verticalAlign=top;align=center;strokeColor=none;image=$imgUri;")
    }
    elseif (-not [string]::IsNullOrWhiteSpace($stencil.MxGraphXml)) {
        # [FIX-11] The MxGraphXml case used to fall through to the default
        # below, so an XML-only stencil silently placed a BLANK RECTANGLE.
        # Lift the style off the model's first vertex instead. Multi-cell
        # models cannot collapse into one cell, so say so rather than
        # rendering a box that looks deliberate.
        $vertexStyle = $null
        try {
            $model    = [xml]$stencil.MxGraphXml
            # [FIX-29] Get-XmlAttr, not $_.id. This filter only exists to
            # skip mxGraph's two root cells, which always carry id="0" and
            # id="1" — but under Set-StrictMode the bare property read threw
            # PropertyNotFoundStrict on any OTHER vertex that happened to
            # omit the attribute, and the catch below then reported the
            # stencil as unusable and told the caller to re-create it. An id
            # is not required on an mxCell, and -MxGraphXml exists precisely
            # to accept hand-written models, so this rejected valid input and
            # blamed the input for it. Line 663 below already did this right.
            $vertices = @($model.SelectNodes('//mxCell[@vertex="1"]') | Where-Object {
                              $vid = Get-XmlAttr -Node $_ -Name 'id'
                              $vid -ne '0' -and $vid -ne '1'
                          })

            if ($vertices.Count -eq 0) {
                throw "the model declares no vertex cells"
            }
            if ($vertices.Count -gt 1) {
                Write-Warning ("Add-DrawShapeFromStencil: stencil '$StencilName' is a " +
                               "$($vertices.Count)-cell group; only the first cell's style " +
                               "is applied. Complex groups are better placed by hand or " +
                               "exported with Export-DrawStencilLibrary.")
            }
            $vertexStyle = Get-XmlAttr -Node $vertices[0] -Name 'style'
        }
        catch {
            throw ("Add-DrawShapeFromStencil: stencil '$StencilName' has MxGraphXml that " +
                   "could not be used ($_). Re-create it with -Style, or import an image-based " +
                   "stencil instead.")
        }

        if ([string]::IsNullOrWhiteSpace($vertexStyle)) {
            throw ("Add-DrawShapeFromStencil: stencil '$StencilName' has MxGraphXml whose " +
                   "first vertex carries no style — there is nothing to render. " +
                   "Re-create it with -Style.")
        }
        $vertexStyle
    }
    elseif (-not [string]::IsNullOrWhiteSpace($stencil.Style)) {
        $stencil.Style
    }
    else {
        throw ("Add-DrawShapeFromStencil: stencil '$StencilName' carries no ImageData, " +
               "MxGraphXml or Style, so it has no appearance. This usually means the " +
               "source stencil failed to import.")
    }

    $cell          = [DrawCell]::new($lbl)
    $cell.Style    = $style
    $cell.X        = $X
    $cell.Y        = $Y
    $cell.Width    = $w
    $cell.Height   = $h
    $cell.Metadata = $Metadata

    if (-not [string]::IsNullOrWhiteSpace($Tooltip)) { $cell.Tooltip = $Tooltip }

    $Page.AddCell($cell)
    Write-Verbose "Add-DrawShapeFromStencil: placed '$StencilName' at ($X, $Y) [${w}x${h}]"

    if ($PassThru) { return $cell }
}