-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuild.ps1
More file actions
752 lines (651 loc) · 29.1 KB
/
Copy pathbuild.ps1
File metadata and controls
752 lines (651 loc) · 29.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
#Requires -Version 7.0
<#
.SYNOPSIS
Unified build, test, and publish script for outlook-cli.
.DESCRIPTION
Builds and tests both the Node.js and .NET implementations.
All building and publishing happens first, then tests run against
both runtimes with a side-by-side timing comparison.
.PARAMETER Target
What to build: 'node', 'dotnet', or 'all'. Default: 'all'.
.PARAMETER Publish
After build+test, publish NativeAOT binaries.
.PARAMETER Runtime
Comma-separated RIDs for publish, or 'all' for all 4 targets.
Default: current platform. Options: win-x64, win-arm64, osx-arm64, linux-x64.
.PARAMETER NoDist
Skip creating the deployment distribution (dist\outlook-cli\).
.PARAMETER TestOnly
Skip build, run tests only.
.PARAMETER NoBuild
Skip build step (useful with -Publish to skip rebuild).
.PARAMETER Integration
Include integration tests (requires live auth for the "agent" account).
Without this flag, only unit/shared/stress tests run.
.PARAMETER Configuration
Build configuration. Default: Release.
.EXAMPLE
.\build.ps1 node # Build + test Node.js
.\build.ps1 dotnet # Build + test .NET
.\build.ps1 all # Build, test, publish for current platform
.\build.ps1 all -NoPublish # Build + test only (skip publish)
.\build.ps1 dotnet -Publish # Build, test, publish for current platform
.\build.ps1 dotnet -Publish -Runtime all # All 4 targets
.\build.ps1 dotnet -Publish -Runtime win-x64,osx-arm64
.\build.ps1 node -TestOnly # Run Node.js tests only
.\build.ps1 all -Integration # Include integration tests (requires auth)
#>
param(
[Parameter(Position = 0)]
[ValidateSet('node', 'dotnet', 'all')]
[string]$Target = 'all',
[switch]$Publish,
[switch]$NoPublish,
[switch]$NoDist,
[string]$Runtime,
[switch]$TestOnly,
[switch]$NoBuild,
[switch]$Integration,
[ValidateSet('Debug', 'Release')]
[string]$Configuration = 'Release'
)
$ErrorActionPreference = 'Stop'
$script:ProjectRoot = $PSScriptRoot
$script:BridgeStarted = $false
$script:DotnetProject = Join-Path $ProjectRoot 'src' 'dotnet' 'OutlookCli.csproj'
$script:BridgeProject = Join-Path $ProjectRoot 'src' 'bridge' 'Microsoft.M365Tool.Bridge.csproj'
$script:PublishDir = Join-Path $ProjectRoot 'publish'
$script:BridgePublishDir = Join-Path $ProjectRoot 'publish-bridge'
$script:DistDir = Join-Path $ProjectRoot 'dist' 'outlook-cli'
# Ensure UTF-8 output so test runner symbols (✓, ○) display correctly
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
$OutputEncoding = [System.Text.Encoding]::UTF8
$AllRuntimes = @('win-x64', 'win-arm64', 'osx-arm64', 'linux-x64')
# Determine current platform RID
function Get-CurrentRid {
if ($IsWindows -or $env:OS -eq 'Windows_NT') {
$arch = [System.Runtime.InteropServices.RuntimeInformation]::OSArchitecture
return ($arch -eq 'Arm64') ? 'win-arm64' : 'win-x64'
}
elseif ($IsMacOS) { return 'osx-arm64' }
elseif ($IsLinux) { return 'linux-x64' }
else { return 'win-x64' }
}
# Get the NativeAOT binary path for the current platform (or $null if not built)
function Get-NativeBinaryPath {
$rid = Get-CurrentRid
$ext = ($rid -like 'win-*') ? '.exe' : ''
$binary = Join-Path $script:PublishDir $rid "outlook-cli$ext"
if (Test-Path $binary) { return $binary }
return $null
}
# Track results for summary table
$script:Results = [System.Collections.Generic.List[PSCustomObject]]::new()
function Add-Result([string]$Step, [bool]$Success, [string]$Detail = '') {
$script:Results.Add([PSCustomObject]@{
Step = $Step
Status = if ($Success) { 'PASS' } else { 'FAIL' }
Detail = $Detail
})
}
function Write-StepHeader([string]$Message) {
Write-Host ""
Write-Host "═══════════════════════════════════════════════════" -ForegroundColor Cyan
Write-Host " $Message" -ForegroundColor Cyan
Write-Host "═══════════════════════════════════════════════════" -ForegroundColor Cyan
}
# ── Node.js ──────────────────────────────────────────────
function Show-TestSkipSummary {
$skips = @()
if ($env:OUTLOOK_CLI_E2E -ne '1') {
$integrationDir = Join-Path $ProjectRoot 'test' 'integration'
$integrationFiles = Get-ChildItem -Path $integrationDir -Filter '*.test.js' -Recurse -ErrorAction SilentlyContinue
if ($integrationFiles) {
$skips += "Integration tests ($($integrationFiles.Count) files): requires real Microsoft account — run: `$env:OUTLOOK_CLI_E2E='1'"
}
}
$nativeBinary = Get-NativeBinaryPath
if (-not $nativeBinary) {
$skips += "NativeAOT binary tests (1 file): run .\build.ps1 all to build the native binary"
}
if ($skips.Count -gt 0) {
Write-Host ""
Write-Host " Skipped test summary:" -ForegroundColor Yellow
foreach ($s in $skips) {
Write-Host " - $s" -ForegroundColor Yellow
}
Write-Host ""
}
}
function Invoke-NodeBuild {
Write-StepHeader "Node.js: Install dependencies"
try {
Push-Location $ProjectRoot
npm install --prefer-offline --no-audit 2>&1 | Out-Host
if ($LASTEXITCODE -ne 0) { throw "npm install failed" }
Add-Result "Node.js install" $true
}
catch {
Add-Result "Node.js install" $false $_.Exception.Message
throw
}
finally { Pop-Location }
}
function Invoke-VitestRun([string]$Label, [string]$ReportFile, [string]$BinOverride) {
Write-StepHeader "Tests: $Label"
try {
Push-Location $ProjectRoot
$savedBin = $env:OUTLOOK_CLI_BIN
if ($BinOverride) {
$env:OUTLOOK_CLI_BIN = $BinOverride
Write-Host " OUTLOOK_CLI_BIN=$BinOverride" -ForegroundColor DarkGray
}
else {
Remove-Item Env:\OUTLOOK_CLI_BIN -ErrorAction SilentlyContinue
}
# By default, exclude integration tests — they require live auth (oauth tokens
# for the "agent" account). Use -Integration to include them.
# This default matches what `npm test` does: --exclude 'test/integration/**'
$excludeArgs = if ($Integration) { @() } else { @('--exclude', 'test/integration/**') }
npx vitest run @excludeArgs --outputFile.json="$ReportFile" 2>&1 | Out-Host
if ($LASTEXITCODE -ne 0) { throw "$Label tests failed" }
Add-Result "$Label tests" $true
}
catch {
Add-Result "$Label tests" $false $_.Exception.Message
}
finally {
# Restore env var
if ($savedBin) { $env:OUTLOOK_CLI_BIN = $savedBin }
else { Remove-Item Env:\OUTLOOK_CLI_BIN -ErrorAction SilentlyContinue }
Pop-Location
}
}
# ── .NET ─────────────────────────────────────────────────
function Invoke-DotnetBuild {
Write-StepHeader ".NET: Build ($Configuration)"
try {
dotnet build $script:DotnetProject -c $Configuration --nologo 2>&1 | Out-Host
if ($LASTEXITCODE -ne 0) { throw "dotnet build failed" }
Add-Result ".NET build" $true
}
catch {
Add-Result ".NET build" $false $_.Exception.Message
throw
}
}
function Invoke-DotnetTest {
$testProject = Join-Path $ProjectRoot 'test' 'dotnet' 'OutlookCli.Tests' 'OutlookCli.Tests.csproj'
if (Test-Path $testProject) {
Write-StepHeader ".NET: Run unit tests"
try {
dotnet test $testProject -c $Configuration --nologo 2>&1 | Out-Host
if ($LASTEXITCODE -ne 0) { throw "dotnet tests failed" }
Add-Result ".NET unit tests" $true
}
catch {
Add-Result ".NET unit tests" $false $_.Exception.Message
}
}
else {
Write-Host " (No .NET test project found — skipping)" -ForegroundColor Yellow
Add-Result ".NET unit tests" $true "(no test project)"
}
}
function Invoke-DotnetPublish([string[]]$Rids) {
foreach ($rid in $Rids) {
Write-StepHeader ".NET: Publish NativeAOT — $rid"
$outDir = Join-Path $script:PublishDir $rid
try {
dotnet publish $script:DotnetProject `
-c $Configuration `
-r $rid `
--self-contained true `
/p:PublishAot=true `
-o $outDir `
--nologo 2>&1 | Out-Host
if ($LASTEXITCODE -ne 0) { throw "publish failed for $rid" }
# Report binary size
$ext = if ($rid -like 'win-*') { '.exe' } else { '' }
$binary = Join-Path $outDir "outlook-cli$ext"
if (Test-Path $binary) {
$sizeMB = [math]::Round((Get-Item $binary).Length / 1MB, 1)
Add-Result "Publish $rid" $true "${sizeMB} MB"
}
else {
Add-Result "Publish $rid" $true "(binary location unknown)"
}
}
catch {
Add-Result "Publish $rid" $false $_.Exception.Message
throw
}
}
}
# ── Bridge publish ───────────────────────────────────────
function Invoke-BridgePublish {
Write-StepHeader ".NET: Publish Bridge"
try {
dotnet publish $script:BridgeProject `
-c $Configuration `
-r win-x64 `
-o $script:BridgePublishDir `
--nologo 2>&1 | Out-Host
if ($LASTEXITCODE -ne 0) { throw "bridge publish failed" }
$binary = Join-Path $script:BridgePublishDir "outlook-bridge.exe"
if (Test-Path $binary) {
$sizeMB = [math]::Round((Get-Item $binary).Length / 1MB, 1)
Add-Result "Publish bridge" $true "${sizeMB} MB"
}
else {
Add-Result "Publish bridge" $true "(binary location unknown)"
}
}
catch {
Add-Result "Publish bridge" $false $_.Exception.Message
throw
}
}
# ── Bridge lifecycle for integration tests ────────────────
function Start-BridgeForIntegration {
Write-StepHeader "Starting Outlook Bridge"
try {
# The bridge-start.ps1 script handles: finding the bridge exe,
# launching Outlook Classic minimized if not running, starting
# the bridge process, and verifying the health endpoint.
$bridgeScript = Join-Path $ProjectRoot 'bridge-start.ps1'
if (-not (Test-Path $bridgeScript)) {
Write-Warning "bridge-start.ps1 not found — skipping bridge startup"
Add-Result "Bridge start" $false "bridge-start.ps1 not found"
return
}
& $bridgeScript
if ($LASTEXITCODE -ne 0) { throw "bridge-start.ps1 failed" }
$script:BridgeStarted = $true
Add-Result "Bridge start" $true
}
catch {
Add-Result "Bridge start" $false $_.Exception.Message
Write-Warning ("Bridge failed to start — integration tests" +
" may fail for COM-dependent features")
}
}
function Stop-BridgeForIntegration {
if (-not $script:BridgeStarted) { return }
try {
$bridgeStopScript = Join-Path $ProjectRoot 'bridge-stop.ps1'
if (Test-Path $bridgeStopScript) {
& $bridgeStopScript
}
}
catch {
Write-Warning "Bridge stop failed: $_"
}
}
# ── Distribution packaging ───────────────────────────────
function Invoke-Package {
Write-StepHeader "Package: Create deployment distribution"
$rid = Get-CurrentRid
$ext = ($rid -like 'win-*') ? '.exe' : ''
$cliBinary = Join-Path $script:PublishDir $rid "outlook-cli$ext"
$bridgeBinary = Join-Path $script:BridgePublishDir "outlook-bridge$ext"
# Verify source binaries exist
if (-not (Test-Path $cliBinary)) {
Add-Result "Package dist" $false "CLI binary not found: $cliBinary"
return
}
if (-not (Test-Path $bridgeBinary)) {
Add-Result "Package dist" $false "Bridge binary not found: $bridgeBinary"
return
}
# Clean and create dist directory
# WHY rename-then-delete: direct Remove-Item often fails because Explorer,
# antivirus, or indexing services hold handles on the directory. Renaming
# first releases the directory lock, then the old copy can be cleaned up.
if (Test-Path $script:DistDir) {
$oldDir = "$($script:DistDir)-old-$(Get-Random)"
try {
Rename-Item $script:DistDir $oldDir -Force -ErrorAction SilentlyContinue
Remove-Item $oldDir -Recurse -Force -ErrorAction SilentlyContinue
}
catch {
# Fallback: delete contents individually
Get-ChildItem $script:DistDir -Recurse -Force | Remove-Item -Force -Recurse -ErrorAction SilentlyContinue
Remove-Item $script:DistDir -Force -ErrorAction SilentlyContinue
}
}
New-Item -ItemType Directory -Path $script:DistDir -Force | Out-Null
# Copy CLI binary and dependencies (exclude PDBs)
$cliDir = Join-Path $script:PublishDir $rid
Get-ChildItem $cliDir -File | Where-Object { $_.Extension -ne '.pdb' } | ForEach-Object {
Copy-Item $_.FullName $script:DistDir
}
# Copy bridge binary and dependencies (exclude PDBs, bridge.json, and static asset files)
# WHY exclude bridge.json: it contains the shared secret and is generated per-machine
# WHY exclude static assets/web.config: not needed for CLI deployment
$excludeFiles = @('.pdb', '.json') # exclude all JSON (bridge.json, deps.json, runtimeconfig.json are copied selectively)
Get-ChildItem $script:BridgePublishDir -File | Where-Object {
$_.Extension -ne '.pdb' -and
$_.Name -ne 'bridge.json' -and
$_.Name -ne 'web.config' -and
$_.Name -ne 'outlook-bridge.staticwebassets.endpoints.json'
} | ForEach-Object {
Copy-Item $_.FullName $script:DistDir
}
# Copy PowerShell scripts
foreach ($script_ in @('bridge-config.ps1', 'bridge-start.ps1', 'bridge-stop.ps1')) {
$scriptPath = Join-Path $ProjectRoot $script_
if (Test-Path $scriptPath) {
Copy-Item $scriptPath $script:DistDir
}
}
# Copy usage documentation into organized subdirectories
# WHY separate dirs: CLI usage, bridge usage, security, and architecture
# serve different audiences and should be independently navigable.
$docsBase = Join-Path $script:DistDir 'docs'
# usage-cli: CLI command reference (mail, calendar, auth, etc.)
$usageCliDir = Join-Path $docsBase 'usage-cli'
New-Item -ItemType Directory -Path $usageCliDir -Force | Out-Null
$usageDir = Join-Path $ProjectRoot 'docs' 'usage'
if (Test-Path $usageDir) {
Get-ChildItem $usageDir -File -Filter '*.md' | ForEach-Object {
Copy-Item $_.FullName $usageCliDir
}
}
# Also include CLI-relevant docs from the main docs folder
foreach ($f in @('DELEGATE-ACCESS.md', 'JSON-INPUT.md', 'MULTI-ACCOUNT.md',
'WATCH-MODE.md', 'DIAGNOSTICS.md', 'troubleshooting.md')) {
$src = Join-Path $ProjectRoot 'docs' $f
if (Test-Path $src) { Copy-Item $src $usageCliDir }
}
# usage-bridge: bridge setup and operations
$usageBridgeDir = Join-Path $docsBase 'usage-bridge'
New-Item -ItemType Directory -Path $usageBridgeDir -Force | Out-Null
foreach ($f in @('self-hosting.md', 'AZURE-SETUP.md', 'operations.md')) {
$src = Join-Path $ProjectRoot 'docs' $f
if (Test-Path $src) { Copy-Item $src $usageBridgeDir }
}
# security: security docs (common to both CLI and bridge)
$securityDir = Join-Path $docsBase 'security'
New-Item -ItemType Directory -Path $securityDir -Force | Out-Null
foreach ($f in @('SECURITY.md', 'SECURITY-DESIGN.md')) {
$src = Join-Path $ProjectRoot 'docs' $f
if (Test-Path $src) { Copy-Item $src $securityDir }
}
# architecture: architecture docs (common to both)
$archDir = Join-Path $docsBase 'architecture'
New-Item -ItemType Directory -Path $archDir -Force | Out-Null
foreach ($f in @('architecture.md', 'DIRECTORY-STRUCTURE.md', 'src-dotnet.md', 'src-node.md')) {
$src = Join-Path $ProjectRoot 'docs' $f
if (Test-Path $src) { Copy-Item $src $archDir }
}
# Create a README for the dist package
$readmePath = Join-Path $script:DistDir 'README.md'
@"
# outlook-cli — Deployment Package
## Contents
- ``outlook-cli.exe`` — CLI for Microsoft Outlook (self-contained, no dependencies)
- ``outlook-bridge.exe`` — COM Bridge server for Classic Outlook (**requires .NET 10 Runtime**)
- ``bridge-config.ps1`` — Configure bridge (generate secret, register accounts)
- ``bridge-start.ps1`` — Start the bridge server
- ``bridge-stop.ps1`` — Stop the bridge server
### Documentation
- ``docs/usage-cli/`` — CLI command reference (mail, calendar, contacts, auth, watch)
- ``docs/usage-bridge/`` — Bridge setup, self-hosting, and operations
- ``docs/security/`` — Security model and design
- ``docs/architecture/`` — System architecture and directory structure
## Quick Start
1. Run ``.\bridge-config.ps1`` to generate a shared secret and register a bridge account
2. Run ``.\bridge-start.ps1`` to start the bridge (Outlook must be open)
3. Run ``.\outlook-cli.exe mail inbox --account bridge`` to read your inbox
## Requirements
- **Windows** with Classic Outlook (Win32) installed
- **.NET 10 Runtime** — required for ``outlook-bridge.exe`` (download from https://dotnet.microsoft.com/download/dotnet/10.0)
- ``outlook-cli.exe`` is fully self-contained (no runtime needed)
## Adding Secondary Mailboxes
``.\bridge-config.ps1 -AddAccount personal``
This queries the bridge for available Outlook stores and lets you pick one.
## Account Management
.\bridge-config.ps1 -ListAccounts # Show configured accounts
.\bridge-config.ps1 -AddAccount <alias> # Add secondary mailbox
.\bridge-config.ps1 -RemoveAccount <alias> # Remove secondary mailbox
"@ | Set-Content -Path $readmePath -Encoding UTF8
# Validate: run outlook-cli --version from the dist directory
try {
$versionOutput = & (Join-Path $script:DistDir "outlook-cli$ext") --version 2>&1
if ($LASTEXITCODE -ne 0) {
Add-Result "Package dist" $false "outlook-cli --version failed: $versionOutput"
return
}
# Count files and total size
$files = Get-ChildItem $script:DistDir -Recurse -File
$totalMB = [math]::Round(($files | Measure-Object -Property Length -Sum).Sum / 1MB, 1)
Add-Result "Package dist" $true "$($files.Count) files, ${totalMB} MB total"
# Create timestamped zip: dist.YYYYMMDD-HHmm.zip
$timestamp = Get-Date -Format 'yyyyMMdd-HHmm'
$zipName = "dist.${timestamp}.zip"
$zipPath = Join-Path $ProjectRoot $zipName
Compress-Archive -Path (Join-Path $script:DistDir '*') -DestinationPath $zipPath -Force
$zipMB = [math]::Round((Get-Item $zipPath).Length / 1MB, 1)
Add-Result "Package zip" $true "$zipName (${zipMB} MB)"
}
catch {
Add-Result "Package dist" $false "Validation failed: $_"
}
}
function Invoke-TestComparison {
$nodeReport = Join-Path $ProjectRoot 'test-results' 'vitest-report-node.json'
$dotnetReport = Join-Path $ProjectRoot 'test-results' 'vitest-report-dotnet.json'
$compareScript = Join-Path $ProjectRoot 'scripts' 'compare-results.js'
if ((Test-Path $nodeReport) -and (Test-Path $dotnetReport) -and (Test-Path $compareScript)) {
Write-StepHeader "Test Comparison: Node.js vs .NET"
node $compareScript --node "$nodeReport" --dotnet "$dotnetReport" 2>&1 | Out-Host
}
elseif ((Test-Path $nodeReport) -and -not (Test-Path $dotnetReport)) {
Show-TestSkipSummary
}
}
# ── Orchestration ────────────────────────────────────────
function Show-Summary {
Write-Host ""
Write-Host "═══════════════════════════════════════════════════" -ForegroundColor White
Write-Host " Build Summary" -ForegroundColor White
Write-Host "═══════════════════════════════════════════════════" -ForegroundColor White
$anyFail = $false
foreach ($r in $script:Results) {
$color = switch ($r.Status) {
'PASS' { 'Green' }
'SKIP' { 'Yellow' }
default { 'Red'; $anyFail = $true }
}
$detail = if ($r.Detail) { " — $($r.Detail)" } else { '' }
Write-Host (" [{0}] {1}{2}" -f $r.Status, $r.Step, $detail) -ForegroundColor $color
}
# Generate the markdown report and print a link to it as the final output line
$reportPath = Generate-MarkdownReport
Write-Host ""
if ($reportPath) {
Write-Host " 📄 Report: $reportPath" -ForegroundColor Cyan
}
Write-Host ""
if ($anyFail) {
Write-Host " ❌ One or more steps FAILED" -ForegroundColor Red
exit 1
}
else {
Write-Host " ✅ All steps passed" -ForegroundColor Green
exit 0
}
}
# ── Markdown Report ──────────────────────────────────────
# Generates a timestamped markdown file in ./results/ summarizing the build and test results.
# This gives a persistent record of each build run for review, CI archives, and demo prep.
function Generate-MarkdownReport {
$resultsDir = Join-Path $ProjectRoot 'results'
if (-not (Test-Path $resultsDir)) {
New-Item -ItemType Directory -Path $resultsDir -Force | Out-Null
}
$timestamp = Get-Date -Format 'yyyyMMdd-HHmm'
$reportFile = Join-Path $resultsDir "RESULTS-$timestamp.md"
$lines = @()
$lines += "# Build Results — $timestamp"
$lines += ""
$lines += "Generated by ``build.ps1`` on ``$(hostname)`` at ``$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')``"
$lines += ""
# Build step summary table
$lines += "## Build Steps"
$lines += ""
$lines += "| Status | Step | Detail |"
$lines += "|--------|------|--------|"
foreach ($r in $script:Results) {
$icon = switch ($r.Status) { 'PASS' { '✅' }; 'SKIP' { '⏭️' }; default { '❌' } }
$detail = if ($r.Detail) { $r.Detail } else { '—' }
$lines += "| $icon $($r.Status) | $($r.Step) | $detail |"
}
$lines += ""
# Parse vitest JSON reports for detailed test counts
$testResultsDir = Join-Path $ProjectRoot 'test-results'
foreach ($label in @('node', 'dotnet')) {
$jsonPath = Join-Path $testResultsDir "vitest-report-$label.json"
if (Test-Path $jsonPath) {
try {
$report = Get-Content $jsonPath -Raw | ConvertFrom-Json
$lines += "## Vitest Results — $($label.Substring(0,1).ToUpper() + $label.Substring(1))"
$lines += ""
$lines += "| Metric | Count |"
$lines += "|--------|-------|"
$lines += "| Total tests | $($report.numTotalTests) |"
$lines += "| Passed | $($report.numPassedTests) |"
$lines += "| Failed | $($report.numFailedTests) |"
$lines += "| Pending | $($report.numPendingTests) |"
$lines += "| Test suites | $($report.numTotalTestSuites) |"
$lines += ""
# List individual test files with pass/fail counts
if ($report.testResults) {
$lines += "### Test Files"
$lines += ""
$lines += "| Status | File | Tests |"
$lines += "|--------|------|-------|"
foreach ($suite in $report.testResults) {
# Extract relative path from the full path
$name = $suite.name
if ($name -match '[/\\](test[/\\].+)$') { $name = $Matches[1] }
$name = $name -replace '\\', '/'
$icon = if ($suite.status -eq 'passed') { '✅' } else { '❌' }
$testCount = ($suite.assertionResults | Measure-Object).Count
$lines += "| $icon | ``$name`` | $testCount |"
}
$lines += ""
}
}
catch {
$lines += "## Vitest Results — $label"
$lines += ""
$lines += "⚠️ Could not parse ``$jsonPath``: $_"
$lines += ""
}
}
}
# Environment info
$lines += "## Environment"
$lines += ""
$lines += "- **Node.js**: $(node --version 2>$null)"
$lines += "- **.NET SDK**: $(dotnet --version 2>$null)"
$lines += "- **OS**: $([System.Runtime.InteropServices.RuntimeInformation]::OSDescription)"
$lines += "- **PowerShell**: $($PSVersionTable.PSVersion)"
$lines += ""
$lines -join "`n" | Set-Content -Path $reportFile -Encoding utf8
return $reportFile
}
# ── Main ─────────────────────────────────────────────────
$doNode = ($Target -eq 'node') -or ($Target -eq 'all')
$doDotnet = ($Target -eq 'dotnet') -or ($Target -eq 'all')
# Clean stale test reports so the comparison never reads outdated data
$testResultsDir = Join-Path $ProjectRoot 'test-results'
if (-not (Test-Path $testResultsDir)) {
New-Item -ItemType Directory -Path $testResultsDir -Force | Out-Null
}
Remove-Item (Join-Path $testResultsDir 'vitest-report-node.json') -ErrorAction SilentlyContinue
Remove-Item (Join-Path $testResultsDir 'vitest-report-dotnet.json') -ErrorAction SilentlyContinue
try {
# ── Phase 1: Build everything ────────────────────────
$shouldPublish = ($Publish -or ($Target -eq 'all')) -and (-not $NoPublish) -and (-not $TestOnly)
if (-not $TestOnly) {
if ($doNode -and -not $NoBuild) { Invoke-NodeBuild }
if ($doDotnet -and -not $NoBuild) { Invoke-DotnetBuild }
# Publish NativeAOT binaries (needed before dotnet test run)
if ($shouldPublish -and $doDotnet) {
$rids = if ($Runtime -eq 'all') {
$AllRuntimes
}
elseif ($Runtime) {
$Runtime -split ','
}
else {
@(Get-CurrentRid)
}
if ($Publish) {
Invoke-DotnetPublish $rids
}
else {
try {
Invoke-DotnetPublish $rids
}
catch {
$last = $script:Results[$script:Results.Count - 1]
$script:Results[$script:Results.Count - 1] = [PSCustomObject]@{
Step = $last.Step
Status = 'SKIP'
Detail = 'NativeAOT requires C++ Desktop Development workload — install via Visual Studio Installer'
}
}
}
# Publish bridge (framework-dependent, always win-x64 for COM interop)
try {
Invoke-BridgePublish
}
catch {
# Bridge publish failure is non-fatal in default mode
if ($Publish) { throw }
}
}
}
# ── Phase 1.5: Start bridge for integration tests ────
if ($Integration) {
Start-BridgeForIntegration
}
# ── Phase 2: Run tests ───────────────────────────────
$nodeReport = Join-Path $testResultsDir 'vitest-report-node.json'
$dotnetReport = Join-Path $testResultsDir 'vitest-report-dotnet.json'
if ($doNode) {
Invoke-VitestRun "Node.js" $nodeReport
}
if ($doDotnet) {
# Run .NET xunit tests (separate test project)
Invoke-DotnetTest
# Run vitest suite against the NativeAOT binary
$nativeBinary = Get-NativeBinaryPath
if ($nativeBinary) {
Invoke-VitestRun "Dotnet" $dotnetReport $nativeBinary
}
else {
Write-Host ""
Write-Host " Skipping dotnet vitest run — no NativeAOT binary found." -ForegroundColor Yellow
Write-Host " Run .\build.ps1 all to build it, or .\build.ps1 dotnet -Publish" -ForegroundColor Yellow
Add-Result "Dotnet tests" $false "NativeAOT binary not found"
}
}
# ── Phase 3: Comparison report ───────────────────────
Invoke-TestComparison
# ── Phase 4: Create deployment distribution ──────────
if (-not $NoDist -and -not $TestOnly -and $shouldPublish) {
Invoke-Package
}
}
catch {
# Error already logged via Add-Result
}
finally {
Stop-BridgeForIntegration
Show-Summary
}