Private/IconPack.ps1

# ============================================================
# DrawManagement — user icon packs (private helpers)
#
# An icon pack is a folder of SVGs the USER supplies — typically a vendor
# set such as VMware's official stencils — that the module must not ship
# itself because the artwork is not licensed for redistribution. The pack
# lives in the user's profile, never in the module folder:
#
# <root>/<pack>/pack.json manifest: name, source, colour, icons[]
# <root>/<pack>/icons/<icon>.svg normalised SVG, original colours
#
# <root> is $env:DRAWMANAGEMENT_ICONPACKS when set, otherwise
# <LocalApplicationData>/DrawManagement/IconPacks.
# ============================================================

$script:DrawIconPackCache = @{}   # "<pack>|<icon>|<colour>" -> style image URI

function Get-DrawIconPackRoot {
    [CmdletBinding()]
    [OutputType([string])]
    param()
    if (-not [string]::IsNullOrWhiteSpace($env:DRAWMANAGEMENT_ICONPACKS)) {
        return $env:DRAWMANAGEMENT_ICONPACKS
    }
    $base = [Environment]::GetFolderPath('LocalApplicationData')
    if ([string]::IsNullOrWhiteSpace($base)) { $base = Join-Path $HOME '.local' 'share' }
    return (Join-Path $base 'DrawManagement' 'IconPacks')
}

function Read-DrawIconPackManifest {
    [CmdletBinding()]
    param([Parameter(Mandatory)][string] $PackDir)
    $file = Join-Path $PackDir 'pack.json'
    if (-not (Test-Path -LiteralPath $file)) { return $null }
    try {
        return (Get-Content -LiteralPath $file -Raw | ConvertFrom-Json)
    }
    catch {
        Write-Warning "DrawManagement: icon pack manifest '$file' is unreadable — $_"
        return $null
    }
}

function ConvertTo-DrawNormalizedSvg {
    <#
    .SYNOPSIS
        Normalises an SVG for use as a draw.io image and measures it.
    .DESCRIPTION
        Returns Svg (text), Width, Height (natural size from the viewBox,
        else width/height attributes, else 48), Cropped, Valid and Stripped.
 
        Valid is $false when the text is not well-formed XML with an <svg>
        root — an error page saved under an .svg name, say. Callers must not
        install such a file: it would be embedded as an image that never
        renders.
 
        Stripped counts active content removed: <script> elements, on*
        event-handler attributes and javascript: links. draw.io shows the
        icon as an image, where none of that runs, but the file also sits in
        the user's profile where it can be opened directly in a browser, and
        an icon has no use for it.
 
        Cropping: some vendor exports (VMware's horizon.svg) place a small
        glyph on a page-sized artboard and clip it to a rect. Drawn as-is the
        glyph is a speck in an empty box. When the SVG has exactly one clip
        rectangle and it covers under a quarter of the viewBox, the viewBox
        is narrowed to that rectangle.
    #>

    [CmdletBinding()]
    param([Parameter(Mandatory)][AllowEmptyString()][string] $Text)

    $result = [PSCustomObject]@{ Svg = $Text; Width = 48.0; Height = 48.0; Cropped = $false; Valid = $false; Stripped = 0 }

    $doc = New-Object System.Xml.XmlDocument
    $doc.XmlResolver = $null
    try { $doc.LoadXml($Text) } catch { return $result }

    $svg = $doc.DocumentElement
    if ($null -eq $svg -or $svg.LocalName -ne 'svg') { return $result }
    $result.Valid = $true

    foreach ($node in @($doc.SelectNodes("//*[local-name()='script']"))) {
        $null = $node.ParentNode.RemoveChild($node)
        $result.Stripped++
    }
    foreach ($el in @($doc.SelectNodes('//*'))) {
        foreach ($a in @($el.Attributes)) {
            $isHandler = ($a.NamespaceURI -eq '' -and $a.LocalName -match '^(?i)on[a-z]+$')
            $isJsLink  = ($a.LocalName -eq 'href' -and
                          ($a.Value -replace '[\s\x00-\x1F]', '') -match '^(?i)javascript:')
            if ($isHandler -or $isJsLink) {
                $null = $el.Attributes.Remove($a)
                $result.Stripped++
            }
        }
    }

    $toNum = {
        param([string]$s)
        if ([string]::IsNullOrWhiteSpace($s)) { return 0.0 }
        $m = [regex]::Match($s, '^\s*([0-9.]+)')
        if (-not $m.Success) { return 0.0 }
        return [double]::Parse($m.Groups[1].Value, [Globalization.CultureInfo]::InvariantCulture)
    }

    $vb = @()
    $vbRaw = $svg.GetAttribute('viewBox')
    if (-not [string]::IsNullOrWhiteSpace($vbRaw)) {
        $vb = @($vbRaw -split '[\s,]+' | Where-Object { $_ -ne '' } | ForEach-Object {
            [double]::Parse($_, [Globalization.CultureInfo]::InvariantCulture)
        })
    }
    if ($vb.Count -eq 4 -and $vb[2] -gt 0 -and $vb[3] -gt 0) {
        $result.Width  = $vb[2]
        $result.Height = $vb[3]
    }
    else {
        $w = & $toNum $svg.GetAttribute('width')
        $h = & $toNum $svg.GetAttribute('height')
        if ($w -gt 0 -and $h -gt 0) { $result.Width = $w; $result.Height = $h }
    }

    # Single clip rectangle much smaller than the artboard -> crop to it.
    if ($vb.Count -eq 4) {
        $rects = New-Object System.Collections.Generic.List[object]
        foreach ($cp in @($doc.GetElementsByTagName('clipPath'))) {
            foreach ($child in @($cp.ChildNodes)) {
                if ($child -isnot [System.Xml.XmlElement]) { continue }
                $target = $child
                if ($child.LocalName -eq 'use') {
                    $href = $child.GetAttribute('href', 'http://www.w3.org/1999/xlink')
                    if ([string]::IsNullOrWhiteSpace($href)) { $href = $child.GetAttribute('href') }
                    if ($href -match '^#(.+)$') {
                        $id = $Matches[1]
                        $target = $doc.SelectNodes("//*[@id='$id']") | Select-Object -First 1
                    }
                }
                if ($null -ne $target -and $target.LocalName -eq 'rect') {
                    $rects.Add([PSCustomObject]@{
                        X = & $toNum $target.GetAttribute('x'); Y = & $toNum $target.GetAttribute('y')
                        W = & $toNum $target.GetAttribute('width'); H = & $toNum $target.GetAttribute('height')
                    })
                }
            }
        }
        $distinct = @($rects | Sort-Object X, Y, W, H -Unique)
        if ($distinct.Count -eq 1) {
            $r = $distinct[0]
            if ($r.W -gt 0 -and $r.H -gt 0 -and ($r.W * $r.H) -lt (0.25 * $vb[2] * $vb[3])) {
                $inv = [Globalization.CultureInfo]::InvariantCulture
                $svg.SetAttribute('viewBox', ('{0} {1} {2} {3}' -f
                    $r.X.ToString($inv), $r.Y.ToString($inv), $r.W.ToString($inv), $r.H.ToString($inv)))
                $svg.RemoveAttribute('width')
                $svg.RemoveAttribute('height')
                $result.Width   = $r.W
                $result.Height  = $r.H
                $result.Cropped = $true
            }
        }
    }

    $result.Svg = $doc.OuterXml
    return $result
}

function Set-DrawSvgColor {
    <#
    .SYNOPSIS
        Recolours a single-colour SVG.
    .DESCRIPTION
        Replaces every fill/stroke colour except white and 'none' with
        -Color, and sets fill on the root <svg> so paths that rely on the
        SVG default (black) take it too. Intended for monochrome vendor
        glyphs; multi-colour artwork should be placed with -KeepColors.
    #>

    [CmdletBinding()]
    [OutputType([string])]
    param(
        [Parameter(Mandatory)][string] $Svg,
        [Parameter(Mandatory)][string] $Color
    )
    $isWhite = { param($c) $c -match '^(?i)(#fff|#ffffff|white)$' }

    $out = [regex]::Replace($Svg,
        '(?i)\b(fill|stroke)(\s*:\s*|\s*=\s*")(#[0-9a-f]{3,8}\b|black)',
        {
            param($m)
            if (& $isWhite $m.Groups[3].Value) { return $m.Value }
            return $m.Groups[1].Value + $m.Groups[2].Value + $Color
        })

    # Paths without any fill inherit from the root element.
    $out = ([regex]'<svg\b(?![^>]*\sfill=)').Replace($out, "<svg fill=`"$Color`"", 1)
    return $out
}

# ── icons.diagrams.net and draw.io library files ──────────────────────
# icons.diagrams.net hosts ~1,000 extra icon sets that are NOT bundled with
# draw.io (Fortinet, Commvault, Arista, IBM Carbon, Material, ...). Each has
# a set page (/sets/<slug>) stating its licence and author, and a draw.io
# library (/libs/<slug>/<ver>/library.xml) whose entries reference
# /assets/<slug>/<ver>/<icon>.svg|png. robots.txt disallows crawling /libs/,
# so the module only fetches a library when the user explicitly installs
# that one set — the same request as the site's "Download library.xml".

$script:DrawDiagramsNetRoot = 'https://icons.diagrams.net'
$script:DrawDiagramsNetSets = $null   # cached slugs from the sitemap

function Get-DrawDiagramsNetSetInfo {
    <#
    .SYNOPSIS
        Reads an icons.diagrams.net set page: title, count, licence, author, library URL.
    #>

    [CmdletBinding()]
    param(
        [Parameter(Mandatory)][string] $Slug,
        [string] $Html
    )
    $page = "$script:DrawDiagramsNetRoot/sets/$Slug"
    if (-not $PSBoundParameters.ContainsKey('Html')) {
        try {
            $Html = (Invoke-WebRequest -Uri $page -UseBasicParsing -TimeoutSec 60 -ErrorAction Stop).Content
        }
        catch {
            throw ("icons.diagrams.net has no set '$Slug' (${page}: $($_.Exception.Message)). " +
                   'Find set names with Find-DrawIconSet.')
        }
    }
    $decode = { param($s) [System.Net.WebUtility]::HtmlDecode($s).Trim() }
    $lib = [regex]::Match($Html, 'href="(https://icons\.diagrams\.net/libs/[^"]+/library\.xml)"')
    if (-not $lib.Success) {
        throw "Get-DrawDiagramsNetSetInfo: no library.xml link on '$page' — the page layout may have changed."
    }
    $by = [regex]::Match($Html, 'By <a href="([^"]+)"[^>]*>([^<]+)</a>')
    [PSCustomObject]@{
        Name      = $Slug
        Title     = & $decode ([regex]::Match($Html, '<h1>([^<]+)</h1>').Groups[1].Value)
        Icons     = [int]('0' + [regex]::Match($Html, '<b>(\d+)</b>\s*icons').Groups[1].Value)
        License   = & $decode ([regex]::Match($Html, 'License:\s*<b>([^<]+)</b>').Groups[1].Value)
        Author    = if ($by.Success) { & $decode $by.Groups[2].Value } else { '' }
        AuthorUrl = if ($by.Success) { & $decode $by.Groups[1].Value } else { '' }
        Page      = $page
        Library   = & $decode $lib.Groups[1].Value
    }
}

function Read-DrawLibraryEntry {
    <#
    .SYNOPSIS
        Parses a draw.io library (<mxlibrary>) into importable icon entries.
    .DESCRIPTION
        Each entry is one of:
          Kind svg|png|jpeg|gif an image: Data (bytes) when embedded as a data
                                 URI, Url when it references a remote file
          Kind style a single styled cell (e.g. Commvault badges:
                                 a coloured rounded box with text); Style + Value
        Entries holding several cells are composite drawings, not icons, and
        are returned with Kind 'skip'.
    #>

    [CmdletBinding()]
    param([Parameter(Mandatory)][string] $Text)

    try { $doc = [xml]$Text } catch { throw "Read-DrawLibraryEntry: not XML — is this a draw.io library file? $_" }
    if ($doc.DocumentElement.Name -ne 'mxlibrary') {
        throw "Read-DrawLibraryEntry: root is <$($doc.DocumentElement.Name)>, expected <mxlibrary> (a draw.io library file)."
    }
    $entries = @($doc.DocumentElement.InnerText | ConvertFrom-Json)

    $kindOf = {
        param([string]$mimeOrExt)
        switch -Regex ($mimeOrExt) {
            'svg'         { 'svg'; break }
            'png'         { 'png'; break }
            'jpe?g'       { 'jpeg'; break }
            'gif'         { 'gif'; break }
            default       { '' }
        }
    }
    $fromDataUri = {
        param([string]$uri)
        $m = [regex]::Match($uri, '^data:image/([a-z0-9.+-]+)(?:;base64)?,(.*)$')
        if (-not $m.Success) { return $null }
        $kind = & $kindOf $m.Groups[1].Value
        if (-not $kind) { return $null }
        try { $bytes = [Convert]::FromBase64String($m.Groups[2].Value) }
        catch { $bytes = [Text.Encoding]::UTF8.GetBytes([uri]::UnescapeDataString($m.Groups[2].Value)) }
        [PSCustomObject]@{ Kind = $kind; Data = $bytes }
    }

    foreach ($e in $entries) {
        $title = if ($e.PSObject.Properties['title'] -and $e.title) { [string]$e.title } else { 'icon' }
        $w = if ($e.PSObject.Properties['w']) { [double]$e.w } else { 48 }
        $h = if ($e.PSObject.Properties['h']) { [double]$e.h } else { 48 }
        $out = [PSCustomObject]@{ Title = $title; W = $w; H = $h; Kind = 'skip'; Data = $null; Url = ''; Style = ''; Value = '' }

        if ($e.PSObject.Properties['data'] -and $e.data) {
            $img = & $fromDataUri ([string]$e.data)
            if ($img) { $out.Kind = $img.Kind; $out.Data = $img.Data }
            $out; continue
        }
        if (-not ($e.PSObject.Properties['xml'] -and $e.xml)) { $out; continue }

        # draw.io stores library xml plain or compressed — same forms as a page
        $raw = [string]$e.xml
        $wrapper = New-Object System.Xml.XmlDocument
        $diag = $wrapper.CreateElement('diagram')
        if ($raw.TrimStart().StartsWith('<')) { $diag.InnerXml = $raw } else { $diag.InnerText = $raw }
        $model = Get-DrawDiagramModel -Diagram $diag -PageName $title 3>$null
        if ($null -eq $model) { $out; continue }

        $cells = @($model.SelectNodes('//mxCell[@vertex="1"]'))
        if ($cells.Count -ne 1) { $out; continue }
        $cell  = $cells[0]
        $style = Get-XmlAttr -Node $cell -Name 'style'
        $value = Get-XmlAttr -Node $cell -Name 'value'
        $geom  = $cell.SelectSingleNode('mxGeometry')
        if ($null -ne $geom) {
            $gw = Get-XmlAttr -Node $geom -Name 'width'; $gh = Get-XmlAttr -Node $geom -Name 'height'
            if ($gw) { $out.W = [double]$gw }; if ($gh) { $out.H = [double]$gh }
        }

        $im = [regex]::Match($style, '(?:^|;)image=([^;]+)')
        if ($im.Success) {
            $ref = $im.Groups[1].Value
            if ($ref -like 'data:*') {
                $img = & $fromDataUri $ref
                if ($img) { $out.Kind = $img.Kind; $out.Data = $img.Data }
            }
            elseif ($ref -match '^https?://') {
                $kind = & $kindOf ([IO.Path]::GetExtension(([uri]$ref).AbsolutePath))
                if ($kind) { $out.Kind = $kind; $out.Url = $ref }
            }
        }
        else {
            $out.Kind  = 'style'
            $out.Style = $style
            $out.Value = $value
        }
        $out
    }
}

function Get-DrawImageKind {
    <#
    .SYNOPSIS
        Identifies a raster image by its signature: 'png', 'jpeg', 'gif' or ''.
    .DESCRIPTION
        A file's extension and a data URI's media type are claims, not facts.
        Reading the first bytes tells a real image from an HTML error page
        served under an image name, and corrects a JPEG published as .png.
    #>

    [CmdletBinding()]
    [OutputType([string])]
    param([Parameter()][AllowNull()][byte[]] $Bytes)

    if ($null -eq $Bytes -or $Bytes.Length -lt 4) { return '' }
    if ($Bytes[0] -eq 0x89 -and $Bytes[1] -eq 0x50 -and $Bytes[2] -eq 0x4E -and $Bytes[3] -eq 0x47) { return 'png' }
    if ($Bytes[0] -eq 0xFF -and $Bytes[1] -eq 0xD8 -and $Bytes[2] -eq 0xFF) { return 'jpeg' }
    if ($Bytes[0] -eq 0x47 -and $Bytes[1] -eq 0x49 -and $Bytes[2] -eq 0x46 -and $Bytes[3] -eq 0x38) { return 'gif' }
    return ''
}

function ConvertTo-DrawIconFileName {
    <#
    .SYNOPSIS
        Turns an icon title into a safe, portable file base name.
    .DESCRIPTION
        Lower case, [a-z0-9_.-] only (so no path separators survive), at most
        80 characters, never empty, never a Windows device name — a library
        entry titled 'AUX' or 'CON' would otherwise fail to write, or write
        to the console, on Windows.
    #>

    [CmdletBinding()]
    [OutputType([string])]
    param([Parameter()][AllowEmptyString()][string] $Title)

    $base = (($Title.ToLowerInvariant() -replace '\s+', '-') -replace '[^a-z0-9_.\-]', '_') -replace '-{2,}', '-'
    if ($base.Length -gt 80) { $base = $base.Substring(0, 80) }
    $base = $base.Trim('-', '.')
    if ([string]::IsNullOrWhiteSpace($base)) { $base = 'icon' }
    if ($base -match '^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$') { $base = "_$base" }
    return $base
}

function Invoke-DrawIconDownload {
    <#
    .SYNOPSIS
        Downloads Url -> Path pairs, a few at a time. Returns the failures.
    .DESCRIPTION
        Throttled to be polite to the host. A single function so that tests
        can mock the network.
    #>

    [CmdletBinding()]
    param([Parameter(Mandatory)][object[]] $Item, [int] $ThrottleLimit = 6)

    $failed = $Item | ForEach-Object -ThrottleLimit $ThrottleLimit -Parallel {
        $ok = $false
        foreach ($try in 1..3) {
            try {
                Invoke-WebRequest -Uri $_.Url -OutFile $_.Path -UseBasicParsing -TimeoutSec 60 -ErrorAction Stop
                $ok = $true; break
            }
            catch { Start-Sleep -Milliseconds (300 * $try) }
        }
        if (-not $ok) { $_ }
    }
    return @($failed)
}