Templates/PowerShellUniversalComponent/component.build.ps1

[CmdletBinding()]
param()

$ErrorActionPreference = 'Stop'
$ModuleName = '<%=$PLASTER_PARAM_ModuleName%>'
$OutputPath = Join-Path $PSScriptRoot 'output' $ModuleName

Push-Location -LiteralPath $PSScriptRoot
try {
    Write-Host 'Installing npm dependencies...' -ForegroundColor Cyan
    npm install --legacy-peer-deps
    if ($LASTEXITCODE -ne 0) {
        throw "Failed to install npm dependencies (exit code $LASTEXITCODE)."
    }

    Write-Host 'Building component...' -ForegroundColor Cyan
    npm run build
    if ($LASTEXITCODE -ne 0) {
        throw "Failed to build component (exit code $LASTEXITCODE)."
    }

    $PublicPath = Join-Path $PSScriptRoot 'public'
    if (-not (Get-ChildItem -LiteralPath $PublicPath -Filter 'index.*.bundle.js' -File)) {
        throw 'Component build did not produce an index.*.bundle.js file.'
    }

    if (Test-Path -LiteralPath $OutputPath) {
        Remove-Item -LiteralPath $OutputPath -Recurse -Force
    }
    New-Item -Path $OutputPath -ItemType Directory -Force | Out-Null

    foreach ($file in "$ModuleName.psd1", "$ModuleName.psm1", 'README.md') {
        Copy-Item -LiteralPath (Join-Path $PSScriptRoot $file) -Destination $OutputPath
    }
    foreach ($folder in 'public', 'private') {
        Copy-Item -LiteralPath (Join-Path $PSScriptRoot $folder) -Destination $OutputPath -Recurse
    }

    Write-Host "Build completed successfully! Module output: $OutputPath" -ForegroundColor Green
}
finally {
    Pop-Location
}