From dc7a8ae143d9bfd7679bb09240f187a4a32d7714 Mon Sep 17 00:00:00 2001 From: Leilei Zhang Date: Fri, 4 Sep 2026 17:18:04 +0800 Subject: [PATCH 1/9] Move release notes into checked-in file Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .pipelines/release.yml | 39 +++++--------------- eng/release/README.md | 17 +++++++++ eng/release/RELEASE_NOTES.md | 50 ++++++++++++++++++++++++++ eng/release/validate_release_notes.ps1 | 40 +++++++++++++++++++++ 4 files changed, 116 insertions(+), 30 deletions(-) create mode 100644 eng/release/README.md create mode 100644 eng/release/RELEASE_NOTES.md create mode 100644 eng/release/validate_release_notes.ps1 diff --git a/.pipelines/release.yml b/.pipelines/release.yml index 5a7f3d04..c50bf0a3 100644 --- a/.pipelines/release.yml +++ b/.pipelines/release.yml @@ -55,6 +55,12 @@ extends: - checkout: self fetchDepth: 0 + - task: PowerShell@2 + displayName: Validate GitHub release notes + inputs: + targetType: filePath + filePath: eng/release/validate_release_notes.ps1 + - task: UseNode@1 displayName: Setup Node.js 24 inputs: @@ -193,11 +199,10 @@ extends: $tag = "$(Build.SourceBranchName)" $version = $tag -replace '^v', '' $isPrerelease = if ($version -match '-') { 'true' } else { 'false' } - $releaseLabel = if ($isPrerelease -eq 'true') { 'Prerelease' } else { 'Release' } + Write-Host "Publishing version: $version" echo "##vso[task.setvariable variable=version;isOutput=true]$version" echo "##vso[task.setvariable variable=isPrerelease;isOutput=true]$isPrerelease" - echo "##vso[task.setvariable variable=releaseLabel;isOutput=true]$releaseLabel" # Update package.json versions $jsPackage = Get-Content "bindings/js/package.json" | ConvertFrom-Json @@ -325,7 +330,6 @@ extends: variables: version: $[ stageDependencies.Build.Build.outputs['SetMeta.version'] ] isPrerelease: $[ stageDependencies.Build.Build.outputs['SetMeta.isPrerelease'] ] - releaseLabel: $[ stageDependencies.Build.Build.outputs['SetMeta.releaseLabel'] ] jobs: - job: create_github_release pool: @@ -352,33 +356,8 @@ extends: tagSource: 'userSpecifiedTag' tag: 'v$(version)' title: 'v$(version)' - releaseNotesSource: 'inline' - releaseNotesInline: | - ## $(releaseLabel) v$(version) - - **Packages:** - - `@microsoft/dynwinrt` - JavaScript/TypeScript bindings for WinRT dynamic invocation - - `@microsoft/dynwinrt-codegen` - Code generation tool for typed WinRT bindings - - `dynwinrt` - Native Python runtime for generated WinRT projections - - `dynwinrt-codegen` - Standalone Python code generation tool - - ## Installation - - ```bash - npm install @microsoft/dynwinrt - npm install -D @microsoft/dynwinrt-codegen - python -m pip install --pre dynwinrt dynwinrt-codegen - ``` - - ## What's Included - - - ✅ Native addons for x64 and ARM64 - - ✅ TypeScript type definitions - - ✅ dynwinrt-codegen CLI for code generation - - ✅ CPython 3.11–3.14 runtime wheels for Windows x64 and ARM64 - - ✅ Standalone Python codegen wheels for Windows x64 and ARM64 - - For usage instructions, see the [README](https://github.com/microsoft/dynwinrt#readme). + releaseNotesSource: 'filePath' + releaseNotesFilePath: '$(Build.SourcesDirectory)/eng/release/RELEASE_NOTES.md' assets: '$(Pipeline.Workspace)/npm-packages/*.tgz' isDraft: false isPreRelease: $(isPrerelease) diff --git a/eng/release/README.md b/eng/release/README.md new file mode 100644 index 00000000..1456dc5b --- /dev/null +++ b/eng/release/README.md @@ -0,0 +1,17 @@ +# Release notes + +`RELEASE_NOTES.md` is the checked-in, curated description for the next public +release. Version-specific installation commands are intentional so each GitHub +Release remains a useful snapshot. + +Before each public release: + +1. Update only `RELEASE_NOTES.md` for the release-note content, including every + version and installation command. +2. Merge the release preparation to `main`. +3. Tag that exact `main` commit. + +Do not edit `.pipelines/release.yml` for each release. The Azure DevOps +`GitHubRelease@1` task reads the notes from the tagged checkout, so the contents +are snapshotted from the tag commit. Its automatic changelog remains enabled +and is appended after the curated notes. diff --git a/eng/release/RELEASE_NOTES.md b/eng/release/RELEASE_NOTES.md new file mode 100644 index 00000000..a28d21a8 --- /dev/null +++ b/eng/release/RELEASE_NOTES.md @@ -0,0 +1,50 @@ +# dynwinrt 0.1.0-preview.22 + +This unified preview improves Python-native WinRT use, expands Classic COM +generation, and adds practical WinUI setup examples. The npm version is +`0.1.0-preview.22`; its Python PEP 440 version is `0.1.0rc22`. + +## Highlights + +- Generated Python async operations now work with `asyncio.create_task()` and + `TaskGroup.create_task()`, while retaining direct `await`, progress, + cancellation, and explicit blocking support. +- `IBuffer` projections provide safe copied byte conversion, and + `unboxObject()`/`unbox_object()` explicitly convert supported boxed + `IPropertyValue` results without changing generic object projection. +- Classic COM codegen now emits validated safe bindings plus generated unsafe + companions and raw ABI support. Complete safe generation covers 5,681 of + 7,929 eligible interfaces in the current Win32 metadata baseline. +- Python projected-lifetime scopes now enforce thread affinity across asyncio + tasks, worker threads, and foreign-thread callbacks. +- New JavaScript and Python WinUI samples demonstrate Windows App SDK + initialization and repeatable WinApp CLI setup. + +## Action required + +- Node.js 18 or later is required. +- Regenerate existing Classic COM bindings. Generated modules now use canonical + `com/` and `com/unsafe/` paths; legacy flat paths are not emitted. +- Import Classic COM through the explicit `@microsoft/dynwinrt/com` entrypoint. + The package root remains WinRT-only, with lower-level access isolated under + `@microsoft/dynwinrt/com/unsafe` and `@microsoft/dynwinrt/com/unsafe/raw`. + +## Install + +```bash +npm install @microsoft/dynwinrt@0.1.0-preview.22 +npm install -D @microsoft/dynwinrt-codegen@0.1.0-preview.22 +python -m pip install --pre "dynwinrt==0.1.0rc22" "dynwinrt-codegen==0.1.0rc22" +``` + +## Packages/platforms + +- `@microsoft/dynwinrt`: JavaScript/TypeScript runtime with Windows x64 and + ARM64 native addons for Node.js 18 or later. +- `@microsoft/dynwinrt-codegen`: typed WinRT and supported Classic COM + generation for JavaScript/TypeScript. +- `dynwinrt`: CPython 3.11-3.14 runtime wheels for Windows x64 and ARM64. +- `dynwinrt-codegen`: standalone Windows x64 and ARM64 wheels that include a + prebuilt generator and require no Rust installation. + +**Detailed changes:** [v0.1.0-preview.21...v0.1.0-preview.22](https://github.com/microsoft/dynwinrt/compare/v0.1.0-preview.21...v0.1.0-preview.22) diff --git a/eng/release/validate_release_notes.ps1 b/eng/release/validate_release_notes.ps1 new file mode 100644 index 00000000..f79ae7d8 --- /dev/null +++ b/eng/release/validate_release_notes.ps1 @@ -0,0 +1,40 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +[CmdletBinding()] +param( + [string]$RepositoryRoot = (Resolve-Path (Join-Path $PSScriptRoot "..\..")).Path +) + +Set-StrictMode -Version Latest +$ErrorActionPreference = "Stop" + +$releaseNotesRelativePath = "eng/release/RELEASE_NOTES.md" +$releaseNotesPath = Join-Path $RepositoryRoot $releaseNotesRelativePath +$pipelinePath = Join-Path $RepositoryRoot ".pipelines/release.yml" + +if (-not (Test-Path -LiteralPath $releaseNotesPath -PathType Leaf)) { + throw "Release notes file is missing: $releaseNotesRelativePath" +} + +$releaseNotes = Get-Content -LiteralPath $releaseNotesPath -Raw +if ([string]::IsNullOrWhiteSpace($releaseNotes)) { + throw "Release notes file is empty: $releaseNotesRelativePath" +} + +$pipeline = Get-Content -LiteralPath $pipelinePath -Raw +$expectedSource = "releaseNotesSource: 'filePath'" +$expectedPath = 'releaseNotesFilePath: ''$(Build.SourcesDirectory)/eng/release/RELEASE_NOTES.md''' +$expectedChangeLog = "addChangeLog: true" + +if (-not $pipeline.Contains($expectedSource)) { + throw "GitHubRelease@1 must use $expectedSource" +} +if (-not $pipeline.Contains($expectedPath)) { + throw "GitHubRelease@1 must reference $releaseNotesRelativePath from Build.SourcesDirectory" +} +if (-not $pipeline.Contains($expectedChangeLog)) { + throw "GitHubRelease@1 must preserve $expectedChangeLog" +} + +Write-Host "Release notes configuration is valid: $releaseNotesRelativePath" From 691346fc7e13eb9bc825bfbbf27013547ab59ede Mon Sep 17 00:00:00 2001 From: Leilei Zhang Date: Fri, 4 Sep 2026 18:08:21 +0800 Subject: [PATCH 2/9] Harden release notes validation Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .pipelines/release.yml | 9 + eng/release/README.md | 8 +- eng/release/test_validate_release_notes.ps1 | 141 +++++++++++++ eng/release/validate_release_notes.ps1 | 213 +++++++++++++++++++- 4 files changed, 356 insertions(+), 15 deletions(-) create mode 100644 eng/release/test_validate_release_notes.ps1 diff --git a/.pipelines/release.yml b/.pipelines/release.yml index c50bf0a3..4ed54926 100644 --- a/.pipelines/release.yml +++ b/.pipelines/release.yml @@ -61,6 +61,12 @@ extends: targetType: filePath filePath: eng/release/validate_release_notes.ps1 + - task: PowerShell@2 + displayName: Test GitHub release notes validation + inputs: + targetType: filePath + filePath: eng/release/test_validate_release_notes.ps1 + - task: UseNode@1 displayName: Setup Node.js 24 inputs: @@ -346,6 +352,9 @@ extends: artifactName: npm-packages targetPath: $(Pipeline.Workspace)/npm-packages steps: + - checkout: self + fetchDepth: 1 + - task: GitHubRelease@1 displayName: Create GitHub Release inputs: diff --git a/eng/release/README.md b/eng/release/README.md index 1456dc5b..40164904 100644 --- a/eng/release/README.md +++ b/eng/release/README.md @@ -11,7 +11,7 @@ Before each public release: 2. Merge the release preparation to `main`. 3. Tag that exact `main` commit. -Do not edit `.pipelines/release.yml` for each release. The Azure DevOps -`GitHubRelease@1` task reads the notes from the tagged checkout, so the contents -are snapshotted from the tag commit. Its automatic changelog remains enabled -and is appended after the curated notes. +Do not edit `.pipelines/release.yml` for each release. The Azure DevOps release +job explicitly checks out the tagged commit before `GitHubRelease@1` reads the +notes, so the contents are snapshotted from the tag commit. Its automatic +changelog remains enabled and is appended after the curated notes. diff --git a/eng/release/test_validate_release_notes.ps1 b/eng/release/test_validate_release_notes.ps1 new file mode 100644 index 00000000..7d36af8e --- /dev/null +++ b/eng/release/test_validate_release_notes.ps1 @@ -0,0 +1,141 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +[CmdletBinding()] +param( + [string]$RepositoryRoot = (Resolve-Path (Join-Path $PSScriptRoot "..\..")).Path +) + +Set-StrictMode -Version Latest +$ErrorActionPreference = "Stop" + +$validatorPath = Join-Path $PSScriptRoot "validate_release_notes.ps1" +$pipelinePath = Join-Path $RepositoryRoot ".pipelines/release.yml" +$releaseNotesPath = Join-Path $RepositoryRoot "eng/release/RELEASE_NOTES.md" +$tempRoot = Join-Path ([IO.Path]::GetTempPath()) "dynwinrt-release-notes-$([guid]::NewGuid())" +$tempPipelinePath = Join-Path $tempRoot ".pipelines/release.yml" +$tempNotesPath = Join-Path $tempRoot "eng/release/RELEASE_NOTES.md" +$utf8NoBom = [Text.UTF8Encoding]::new($false) + +function Write-TestFile { + param( + [string]$Path, + [string]$Contents + ) + + [IO.File]::WriteAllText($Path, $Contents, $utf8NoBom) +} + +function Assert-ValidationFails { + param( + [string]$Name, + [string]$Pipeline, + [AllowEmptyString()][string]$Notes, + [bool]$CreateNotes, + [string]$ExpectedMessage + ) + + Write-TestFile -Path $tempPipelinePath -Contents $Pipeline + if ($CreateNotes) { + Write-TestFile -Path $tempNotesPath -Contents $Notes + } else { + Remove-Item -LiteralPath $tempNotesPath -Force -ErrorAction SilentlyContinue + } + + try { + & $validatorPath -RepositoryRoot $tempRoot | Out-Null + throw "Expected validation failure for '$Name'" + } catch { + if ($_.Exception.Message -notlike $ExpectedMessage) { + throw "Unexpected failure for '$Name': $($_.Exception.Message)" + } + } + + Write-Host "Rejected invalid configuration: $Name" +} + +& $validatorPath -RepositoryRoot $RepositoryRoot + +$validPipeline = Get-Content -LiteralPath $pipelinePath -Raw +$validNotes = Get-Content -LiteralPath $releaseNotesPath -Raw +$newline = if ($validPipeline.Contains("`r`n")) { "`r`n" } else { "`n" } + +New-Item -ItemType Directory -Force -Path ` + (Split-Path $tempPipelinePath -Parent), ` + (Split-Path $tempNotesPath -Parent) | Out-Null + +try { + $commentedExpectedValues = @( + " releaseNotesSource: 'inline'" + " # releaseNotesSource: 'filePath'" + ' # releaseNotesFilePath: ''$(Build.SourcesDirectory)/eng/release/RELEASE_NOTES.md''' + " # addChangeLog: true" + ) -join $newline + $commentedPipeline = $validPipeline.Replace( + " releaseNotesSource: 'filePath'", + $commentedExpectedValues + ) + Assert-ValidationFails -Name "expected values only in comments" ` + -Pipeline $commentedPipeline -Notes $validNotes -CreateNotes $true ` + -ExpectedMessage "*releaseNotesSource*must be 'filePath'*" + + $activeInlinePipeline = $validPipeline.Replace( + " releaseNotesSource: 'filePath'", + " releaseNotesSource: 'inline'" + ) + $unrelatedExpectedValues = @( + " - task: PowerShell@2" + " displayName: Unrelated expected values" + " inputs:" + " targetType: inline" + " script: Write-Host test" + " env:" + " releaseNotesSource: 'filePath'" + ' releaseNotesFilePath: ''$(Build.SourcesDirectory)/eng/release/RELEASE_NOTES.md''' + " addChangeLog: true" + "" + " - task: GitHubRelease@1" + ) -join $newline + $unrelatedPipeline = $activeInlinePipeline.Replace( + " - task: GitHubRelease@1", + $unrelatedExpectedValues + ) + Assert-ValidationFails -Name "expected values on an unrelated task" ` + -Pipeline $unrelatedPipeline -Notes $validNotes -CreateNotes $true ` + -ExpectedMessage "*releaseNotesSource*must be 'filePath'*" + + $wrongPathPipeline = $validPipeline.Replace( + 'releaseNotesFilePath: ''$(Build.SourcesDirectory)/eng/release/RELEASE_NOTES.md''', + 'releaseNotesFilePath: ''$(Build.SourcesDirectory)/eng/release/BROKEN.md''' + ) + Assert-ValidationFails -Name "wrong active release notes path" ` + -Pipeline $wrongPathPipeline -Notes $validNotes -CreateNotes $true ` + -ExpectedMessage "*releaseNotesFilePath*RELEASE_NOTES.md*BROKEN.md*" + + $disabledChangeLogPipeline = $validPipeline.Replace( + "addChangeLog: true", + "addChangeLog: false" + ) + Assert-ValidationFails -Name "disabled active changelog" ` + -Pipeline $disabledChangeLogPipeline -Notes $validNotes -CreateNotes $true ` + -ExpectedMessage "*addChangeLog*must be 'true'*" + + $checkoutBlock = " - checkout: self${newline} fetchDepth: 1" + $checkoutNoneBlock = " - checkout: none${newline} # - checkout: self${newline} # fetchDepth: 1" + $missingCheckoutPipeline = $validPipeline.Replace($checkoutBlock, $checkoutNoneBlock) + Assert-ValidationFails -Name "release job source checkout unavailable" ` + -Pipeline $missingCheckoutPipeline -Notes $validNotes -CreateNotes $true ` + -ExpectedMessage "*explicitly checkout 'self'*" + + Assert-ValidationFails -Name "empty release notes" ` + -Pipeline $validPipeline -Notes "" -CreateNotes $true ` + -ExpectedMessage "Release notes file is empty:*" + + Assert-ValidationFails -Name "missing release notes" ` + -Pipeline $validPipeline -Notes "" -CreateNotes $false ` + -ExpectedMessage "Release notes file is missing:*" +} finally { + Remove-Item -LiteralPath $tempRoot -Recurse -Force -ErrorAction SilentlyContinue +} + +Write-Host "Release notes validation regression tests passed" diff --git a/eng/release/validate_release_notes.ps1 b/eng/release/validate_release_notes.ps1 index f79ae7d8..6ce8d457 100644 --- a/eng/release/validate_release_notes.ps1 +++ b/eng/release/validate_release_notes.ps1 @@ -9,6 +9,92 @@ param( Set-StrictMode -Version Latest $ErrorActionPreference = "Stop" +function Get-Indent { + param([string]$Line) + + return $Line.Length - $Line.TrimStart().Length +} + +function Get-BlockEnd { + param( + [string[]]$Lines, + [int]$Start, + [int]$Indent + ) + + for ($index = $Start + 1; $index -lt $Lines.Count; $index++) { + $trimmed = $Lines[$index].Trim() + if (-not $trimmed -or $trimmed.StartsWith("#")) { + continue + } + if ((Get-Indent $Lines[$index]) -le $Indent) { + return $index + } + } + + return $Lines.Count +} + +function ConvertFrom-YamlScalar { + param([string]$Value) + + $valueWithoutComment = ($Value -split "\s+#", 2)[0].Trim() + if ($valueWithoutComment -match "^'(?(?:[^']|'')*)'$") { + return $Matches.value.Replace("''", "'") + } + if ($valueWithoutComment -match '^"(?[^"]*)"$') { + return $Matches.value + } + return $valueWithoutComment +} + +function Get-DirectMapping { + param( + [string[]]$Lines, + [int]$Start, + [int]$End, + [int]$ParentIndent + ) + + $mapping = @{} + $entryIndent = $ParentIndent + 2 + for ($index = $Start + 1; $index -lt $End; $index++) { + $trimmed = $Lines[$index].Trim() + if (-not $trimmed -or $trimmed.StartsWith("#")) { + continue + } + if ((Get-Indent $Lines[$index]) -ne $entryIndent) { + continue + } + if ($Lines[$index] -notmatch "^\s*(?[A-Za-z][A-Za-z0-9]*):\s*(?.*?)\s*$") { + continue + } + + $key = $Matches.key + if ($mapping.ContainsKey($key)) { + throw "Duplicate '$key' entry in active YAML mapping" + } + $mapping[$key] = ConvertFrom-YamlScalar $Matches.value + } + + return $mapping +} + +function Assert-TaskInput { + param( + [hashtable]$Inputs, + [string]$Name, + [string]$Expected + ) + + if (-not $Inputs.ContainsKey($Name)) { + throw "GitHubRelease@1 input '$Name' is missing" + } + if ($Inputs[$Name] -cne $Expected) { + throw "GitHubRelease@1 input '$Name' must be '$Expected', got '$($Inputs[$Name])'" + } +} + $releaseNotesRelativePath = "eng/release/RELEASE_NOTES.md" $releaseNotesPath = Join-Path $RepositoryRoot $releaseNotesRelativePath $pipelinePath = Join-Path $RepositoryRoot ".pipelines/release.yml" @@ -22,19 +108,124 @@ if ([string]::IsNullOrWhiteSpace($releaseNotes)) { throw "Release notes file is empty: $releaseNotesRelativePath" } -$pipeline = Get-Content -LiteralPath $pipelinePath -Raw -$expectedSource = "releaseNotesSource: 'filePath'" -$expectedPath = 'releaseNotesFilePath: ''$(Build.SourcesDirectory)/eng/release/RELEASE_NOTES.md''' -$expectedChangeLog = "addChangeLog: true" +$lines = @(Get-Content -LiteralPath $pipelinePath) +$taskMatches = @() +for ($index = 0; $index -lt $lines.Count; $index++) { + if ($lines[$index] -match "^(?\s*)-\s+task:\s*GitHubRelease@1\s*(?:#.*)?$") { + $taskMatches += [pscustomobject]@{ + Index = $index + Indent = $Matches.indent.Length + } + } +} -if (-not $pipeline.Contains($expectedSource)) { - throw "GitHubRelease@1 must use $expectedSource" +if ($taskMatches.Count -ne 1) { + throw "Expected exactly one active GitHubRelease@1 task, found $($taskMatches.Count)" } -if (-not $pipeline.Contains($expectedPath)) { - throw "GitHubRelease@1 must reference $releaseNotesRelativePath from Build.SourcesDirectory" + +$taskIndex = $taskMatches[0].Index +$taskIndent = $taskMatches[0].Indent +$taskEnd = Get-BlockEnd -Lines $lines -Start $taskIndex -Indent $taskIndent + +$inputsMatches = @() +for ($index = $taskIndex + 1; $index -lt $taskEnd; $index++) { + if ((Get-Indent $lines[$index]) -eq ($taskIndent + 2) -and + $lines[$index] -match "^\s*inputs:\s*(?:#.*)?$") { + $inputsMatches += $index + } } -if (-not $pipeline.Contains($expectedChangeLog)) { - throw "GitHubRelease@1 must preserve $expectedChangeLog" +if ($inputsMatches.Count -ne 1) { + throw "Expected exactly one active inputs block for GitHubRelease@1, found $($inputsMatches.Count)" +} + +$inputsIndex = $inputsMatches[0] +$inputsIndent = Get-Indent $lines[$inputsIndex] +$inputsEnd = Get-BlockEnd -Lines $lines -Start $inputsIndex -Indent $inputsIndent +$inputs = Get-DirectMapping -Lines $lines -Start $inputsIndex -End $inputsEnd -ParentIndent $inputsIndent + +Assert-TaskInput -Inputs $inputs -Name "releaseNotesSource" -Expected "filePath" +Assert-TaskInput -Inputs $inputs -Name "releaseNotesFilePath" ` + -Expected '$(Build.SourcesDirectory)/eng/release/RELEASE_NOTES.md' +Assert-TaskInput -Inputs $inputs -Name "addChangeLog" -Expected "true" + +$jobIndex = -1 +$jobIndent = -1 +for ($index = $taskIndex - 1; $index -ge 0; $index--) { + if ($lines[$index] -match "^(?\s*)-\s+job:\s*(?[^#\s]+)\s*(?:#.*)?$" -and + $Matches.indent.Length -lt $taskIndent) { + $jobIndex = $index + $jobIndent = $Matches.indent.Length + break + } +} +if ($jobIndex -lt 0) { + throw "GitHubRelease@1 is not inside an active job" +} + +$jobEnd = Get-BlockEnd -Lines $lines -Start $jobIndex -Indent $jobIndent +if ($taskIndex -ge $jobEnd) { + throw "GitHubRelease@1 is not inside the active job block" +} + +$stepsMatches = @() +$templateContextMatches = @() +for ($index = $jobIndex + 1; $index -lt $jobEnd; $index++) { + if ((Get-Indent $lines[$index]) -ne ($jobIndent + 2)) { + continue + } + if ($lines[$index] -match "^\s*steps:\s*(?:#.*)?$") { + $stepsMatches += $index + } + if ($lines[$index] -match "^\s*templateContext:\s*(?:#.*)?$") { + $templateContextMatches += $index + } +} +if ($stepsMatches.Count -ne 1) { + throw "GitHubRelease@1 job must have exactly one active steps block" +} + +$stepsIndex = $stepsMatches[0] +$stepsIndent = Get-Indent $lines[$stepsIndex] +$stepsEnd = Get-BlockEnd -Lines $lines -Start $stepsIndex -Indent $stepsIndent +if ($taskIndex -le $stepsIndex -or $taskIndex -ge $stepsEnd) { + throw "GitHubRelease@1 must be inside the release job's active steps block" +} +if ($templateContextMatches.Count -ne 1) { + throw "GitHubRelease@1 job must have exactly one active templateContext block" +} + +$templateContextIndex = $templateContextMatches[0] +$templateContextIndent = Get-Indent $lines[$templateContextIndex] +$templateContextEnd = Get-BlockEnd -Lines $lines -Start $templateContextIndex ` + -Indent $templateContextIndent +$templateContext = Get-DirectMapping -Lines $lines -Start $templateContextIndex ` + -End $templateContextEnd -ParentIndent $templateContextIndent +if (-not $templateContext.ContainsKey("type") -or + $templateContext["type"] -cne "releaseJob") { + throw "GitHubRelease@1 job must use templateContext type 'releaseJob'" +} + +$stepIndent = $stepsIndent + 2 +$checkoutMatches = @() +for ($index = $stepsIndex + 1; $index -lt $taskIndex; $index++) { + if ((Get-Indent $lines[$index]) -eq $stepIndent -and + $lines[$index] -match "^\s*-\s+checkout:\s*(?[^#\s]+)\s*(?:#.*)?$") { + $checkoutMatches += [pscustomobject]@{ + Index = $index + Value = $Matches.value + } + } +} +if ($checkoutMatches.Count -ne 1 -or $checkoutMatches[0].Value -cne "self") { + throw "GitHubRelease@1 release job must explicitly checkout 'self' before the task" +} + +$checkoutIndex = $checkoutMatches[0].Index +$checkoutEnd = Get-BlockEnd -Lines $lines -Start $checkoutIndex -Indent $stepIndent +$checkout = Get-DirectMapping -Lines $lines -Start $checkoutIndex -End $checkoutEnd ` + -ParentIndent $stepIndent +if (-not $checkout.ContainsKey("fetchDepth") -or $checkout["fetchDepth"] -cne "1") { + throw "GitHubRelease@1 release job checkout must use fetchDepth '1'" } -Write-Host "Release notes configuration is valid: $releaseNotesRelativePath" +Write-Host "Release notes configuration is valid: $releaseNotesRelativePath is available from the release job checkout" From 76513872243191970bcfdba8961b2e08b6379bb8 Mon Sep 17 00:00:00 2001 From: Leilei Zhang Date: Fri, 4 Sep 2026 18:12:15 +0800 Subject: [PATCH 3/9] Handle quoted release task scalars Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- eng/release/test_validate_release_notes.ps1 | 48 ++++++++++++++++++++- eng/release/validate_release_notes.ps1 | 15 +++++-- 2 files changed, 58 insertions(+), 5 deletions(-) diff --git a/eng/release/test_validate_release_notes.ps1 b/eng/release/test_validate_release_notes.ps1 index 7d36af8e..2a872d46 100644 --- a/eng/release/test_validate_release_notes.ps1 +++ b/eng/release/test_validate_release_notes.ps1 @@ -54,6 +54,19 @@ function Assert-ValidationFails { Write-Host "Rejected invalid configuration: $Name" } +function Assert-ValidationPasses { + param( + [string]$Name, + [string]$Pipeline, + [string]$Notes + ) + + Write-TestFile -Path $tempPipelinePath -Contents $Pipeline + Write-TestFile -Path $tempNotesPath -Contents $Notes + & $validatorPath -RepositoryRoot $tempRoot | Out-Null + Write-Host "Accepted valid configuration: $Name" +} + & $validatorPath -RepositoryRoot $RepositoryRoot $validPipeline = Get-Content -LiteralPath $pipelinePath -Raw @@ -65,6 +78,40 @@ New-Item -ItemType Directory -Force -Path ` (Split-Path $tempNotesPath -Parent) | Out-Null try { + $checkoutBlock = " - checkout: self${newline} fetchDepth: 1" + $singleTaskDoubleCheckout = $validPipeline.Replace( + " - task: GitHubRelease@1", + " - task: 'GitHubRelease@1'" + ).Replace( + $checkoutBlock, + " - checkout: `"self`"${newline} fetchDepth: 1" + ) + Assert-ValidationPasses -Name "single-quoted task and double-quoted checkout" ` + -Pipeline $singleTaskDoubleCheckout -Notes $validNotes + + $doubleTaskSingleCheckout = $validPipeline.Replace( + " - task: GitHubRelease@1", + " - task: `"GitHubRelease@1`"" + ).Replace( + $checkoutBlock, + " - checkout: 'self'${newline} fetchDepth: 1" + ) + Assert-ValidationPasses -Name "double-quoted task and single-quoted checkout" ` + -Pipeline $doubleTaskSingleCheckout -Notes $validNotes + + $quotedDuplicateTasks = @( + " - task: 'GitHubRelease@1'" + "" + " - task: `"GitHubRelease@1`"" + ) -join $newline + $duplicateTaskPipeline = $validPipeline.Replace( + " - task: GitHubRelease@1", + $quotedDuplicateTasks + ) + Assert-ValidationFails -Name "quoted duplicate GitHub release task" ` + -Pipeline $duplicateTaskPipeline -Notes $validNotes -CreateNotes $true ` + -ExpectedMessage "Expected exactly one active GitHubRelease@1 task, found 2" + $commentedExpectedValues = @( " releaseNotesSource: 'inline'" " # releaseNotesSource: 'filePath'" @@ -120,7 +167,6 @@ try { -Pipeline $disabledChangeLogPipeline -Notes $validNotes -CreateNotes $true ` -ExpectedMessage "*addChangeLog*must be 'true'*" - $checkoutBlock = " - checkout: self${newline} fetchDepth: 1" $checkoutNoneBlock = " - checkout: none${newline} # - checkout: self${newline} # fetchDepth: 1" $missingCheckoutPipeline = $validPipeline.Replace($checkoutBlock, $checkoutNoneBlock) Assert-ValidationFails -Name "release job source checkout unavailable" ` diff --git a/eng/release/validate_release_notes.ps1 b/eng/release/validate_release_notes.ps1 index 6ce8d457..2e9ce1d9 100644 --- a/eng/release/validate_release_notes.ps1 +++ b/eng/release/validate_release_notes.ps1 @@ -109,12 +109,18 @@ if ([string]::IsNullOrWhiteSpace($releaseNotes)) { } $lines = @(Get-Content -LiteralPath $pipelinePath) +$yamlScalarPattern = "'(?:[^']|'')*'|`"[^`"]*`"|[^#\s]+" $taskMatches = @() for ($index = 0; $index -lt $lines.Count; $index++) { - if ($lines[$index] -match "^(?\s*)-\s+task:\s*GitHubRelease@1\s*(?:#.*)?$") { + if ($lines[$index] -match "^(?\s*)-\s+task:\s*(?$yamlScalarPattern)\s*(?:#.*)?$") { + $taskIndent = $Matches.indent.Length + $taskValue = ConvertFrom-YamlScalar $Matches.value + if ($taskValue -cne "GitHubRelease@1") { + continue + } $taskMatches += [pscustomobject]@{ Index = $index - Indent = $Matches.indent.Length + Indent = $taskIndent } } } @@ -209,10 +215,11 @@ $stepIndent = $stepsIndent + 2 $checkoutMatches = @() for ($index = $stepsIndex + 1; $index -lt $taskIndex; $index++) { if ((Get-Indent $lines[$index]) -eq $stepIndent -and - $lines[$index] -match "^\s*-\s+checkout:\s*(?[^#\s]+)\s*(?:#.*)?$") { + $lines[$index] -match "^\s*-\s+checkout:\s*(?$yamlScalarPattern)\s*(?:#.*)?$") { + $checkoutValue = ConvertFrom-YamlScalar $Matches.value $checkoutMatches += [pscustomobject]@{ Index = $index - Value = $Matches.value + Value = $checkoutValue } } } From 9e2bdd93cb09d933684411dda558bc6c4943298b Mon Sep 17 00:00:00 2001 From: Leilei Zhang Date: Thu, 10 Sep 2026 21:35:43 +0800 Subject: [PATCH 4/9] Refresh preview.22 release notes from current main Summarize merged changes since v0.1.0-preview.21 through main e7469c8, including Node.js and Python WinRT interface implementations, safe COM additions, Python fixes, and Windows samples. Preserve the release pipeline and pinned package versions. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- eng/release/RELEASE_NOTES.md | 105 +++++++++++++++++++++++++++-------- 1 file changed, 82 insertions(+), 23 deletions(-) diff --git a/eng/release/RELEASE_NOTES.md b/eng/release/RELEASE_NOTES.md index a28d21a8..8f5c7041 100644 --- a/eng/release/RELEASE_NOTES.md +++ b/eng/release/RELEASE_NOTES.md @@ -1,37 +1,93 @@ # dynwinrt 0.1.0-preview.22 -This unified preview improves Python-native WinRT use, expands Classic COM -generation, and adds practical WinUI setup examples. The npm version is -`0.1.0-preview.22`; its Python PEP 440 version is `0.1.0rc22`. +This preview adds standalone WinRT interface implementations, expands safe +Classic COM access, and improves Python usability and Windows examples. +The npm version is `0.1.0-preview.22`; its Python PEP 440 version is `0.1.0rc22`. ## Highlights -- Generated Python async operations now work with `asyncio.create_task()` and - `TaskGroup.create_task()`, while retaining direct `await`, progress, - cancellation, and explicit blocking support. -- `IBuffer` projections provide safe copied byte conversion, and - `unboxObject()`/`unbox_object()` explicitly convert supported boxed - `IPropertyValue` results without changing generic object projection. -- Classic COM codegen now emits validated safe bindings plus generated unsafe - companions and raw ABI support. Complete safe generation covers 5,681 of - 7,929 eligible interfaces in the current Win32 metadata baseline. -- Python projected-lifetime scopes now enforce thread affinity across asyncio - tasks, worker threads, and foreign-thread callbacks. -- New JavaScript and Python WinUI samples demonstrate Windows App SDK - initialization and repeatable WinApp CLI setup. +- **Implement WinRT interfaces in Node.js/TypeScript and Python.** + `IBackgroundTask.implement(handlers)` and other supported interface factories + create standalone `IInspectable` objects without a composable WinUI base. + The typed management handle exposes a stable `impl.value` and `impl.dispose()`; + Python also supports `with IBackgroundTask.implement(handler) as impl:`. + Generated handler declarations cover supported methods, properties, events, + structs, arrays, and multiple outputs. See the + [interface implementation guide and samples](https://github.com/microsoft/dynwinrt/blob/main/docs/guides/windows/winrt-interface-implementations.md). +- **Expanded safe Classic COM for JavaScript/TypeScript.** More exact contracts + enable `IWbemServices` conditional outputs and owned thumbnail handles. + `DynComAudioFormat` validates packed, variable-length `WAVEFORMATEX` headers + and `cbSize` extensions; safe `IAudioClient`/`IAudioClient2`/`IAudioClient3` + projections manage CoTaskMem-owned format outputs. Dedicated + `FORMATETC`/`STGMEDIUM` support covers target-device-independent + `TYMED_HGLOBAL` transfers. +- **Typed COM acquisition and bounded copies.** `projectAs(...)`, restricted + in-process `IMMDevice.activate(InterfaceClass)`, and Promise-based + `activateAudioInterfaceAsync(...)` simplify managed interface acquisition. + Owned-copy APIs cover audio render/capture, STA-only BGRA8 WIC reads, and + linear Media Foundation buffers without exposing borrowed native memory. + Audio/MF copy facades are not complete interface projections. Generated + unsafe companions and raw ABI access remain explicit escape hatches, not + general safe COM support. + See the [Classic COM usage guide](https://github.com/microsoft/dynwinrt/blob/main/docs/guides/windows/classic-com-usage.md). +- **Python asyncio task integration.** Generated operations work with + `asyncio.create_task()` and `TaskGroup.create_task()`, while retaining direct + `await`, progress, cancellation, and explicit blocking through `wait()`. +- **Copied bytes and explicit unboxing.** `IBuffer` projections provide safe + copied byte conversion, and `unboxObject()`/`unbox_object()` explicitly convert + supported boxed `IPropertyValue` results without changing generic object + projection. +- **WinUI examples and repeatable setup.** New + [JavaScript](https://github.com/microsoft/dynwinrt/blob/main/samples/js/winui-tic-tac-toe-code-only/README.md) + samples and refreshed + [Python examples](https://github.com/microsoft/dynwinrt/blob/main/samples/python/winui-hello-world/README.md) + demonstrate Windows App SDK initialization and restoring pinned SDK inputs + with WinApp CLI. +- **Local AI chat in Electron.** The + [Aion Instruct sample](https://github.com/microsoft/dynwinrt/blob/main/samples/js/electron-aion-chat/README.md) + demonstrates streaming responses, cancellation, and multi-turn conversations + through generated WinRT bindings. It requires Windows 11 on an ARM64 + Snapdragon Copilot+ PC, the Aion preview framework, and its QNN provider. + +WinRT implementation callbacks are synchronous, non-agile, and owner-thread-only; +arbitrary generic implementation roots remain unsupported. The `IBackgroundTask` +samples demonstrate controlled native calls, not OS background activation. +These factories do not provide task registration/triggers, CLSID activation, +package deployment, or COM local-server hosting. + +## Improvements and fixes + +Python projected-lifetime scopes now enforce thread affinity: same-thread +asyncio tasks can share a scope, while worker threads must create their own +and native callbacks do not inherit a foreign scope. Async progress handlers +are deactivated on completion, cancellation, or release. Generated JavaScript +WinRT subscriptions release temporary delegate references; retaining an +unsubscribe function no longer keeps a removed handler alive. ## Action required -- Node.js 18 or later is required. -- Regenerate existing Classic COM bindings. Generated modules now use canonical - `com/` and `com/unsafe/` paths; legacy flat paths are not emitted. -- Import Classic COM through the explicit `@microsoft/dynwinrt/com` entrypoint. - The package root remains WinRT-only, with lower-level access isolated under +- Use Node.js 18 or later, keep runtime and codegen versions matched, and + regenerate affected bindings. +- Fully regenerate Classic COM bindings; do not mix old and new modules. + Outputs use canonical `com/` and `com/unsafe/` paths, not legacy flat paths. + Import COM through the explicit `@microsoft/dynwinrt/com` entrypoint. + Runtime and generated package roots remain WinRT-only, with lower-level + runtime access isolated under `@microsoft/dynwinrt/com/unsafe` and `@microsoft/dynwinrt/com/unsafe/raw`. +- Ambiguous COM overloads now use explicit + `AtSlot` names; use the generated declarations + instead of an ambiguous unsuffixed call. +- Python `Char16[]` results now match `list[str]`. Regeneration can change + affected long module paths and ambiguous helper/root imports; use generated + namespace exports rather than constructing names. +- The first typed incremental Python generation over an older package may + need its original WinMD/`--ref` inputs. Supply them or fully regenerate; + missing metadata fails without replacing the previous output. See the + [generator upgrade guidance](https://github.com/microsoft/dynwinrt/blob/main/tools/dynwinrt-codegen/README.md). ## Install -```bash +```powershell npm install @microsoft/dynwinrt@0.1.0-preview.22 npm install -D @microsoft/dynwinrt-codegen@0.1.0-preview.22 python -m pip install --pre "dynwinrt==0.1.0rc22" "dynwinrt-codegen==0.1.0rc22" @@ -42,9 +98,12 @@ python -m pip install --pre "dynwinrt==0.1.0rc22" "dynwinrt-codegen==0.1.0rc22" - `@microsoft/dynwinrt`: JavaScript/TypeScript runtime with Windows x64 and ARM64 native addons for Node.js 18 or later. - `@microsoft/dynwinrt-codegen`: typed WinRT and supported Classic COM - generation for JavaScript/TypeScript. + generation for JavaScript/TypeScript, emitting `.js` and `.d.ts` files. - `dynwinrt`: CPython 3.11-3.14 runtime wheels for Windows x64 and ARM64. - `dynwinrt-codegen`: standalone Windows x64 and ARM64 wheels that include a prebuilt generator and require no Rust installation. +Consuming the packaged binaries and generated bindings requires no native +compiler. Python code generation remains WinRT-only. + **Detailed changes:** [v0.1.0-preview.21...v0.1.0-preview.22](https://github.com/microsoft/dynwinrt/compare/v0.1.0-preview.21...v0.1.0-preview.22) From 113b37b783596f966d667d9f05634eb2a83d9d01 Mon Sep 17 00:00:00 2001 From: Leilei Zhang Date: Fri, 18 Sep 2026 14:35:15 +0800 Subject: [PATCH 5/9] Parallelize CI with verified artifacts and docs-only gates Start Rust validation and configuration-specific producers independently, reuse verified native artifacts in E2E, and retain stable fail-closed success checks. Add a conservative full-PR documentation-only lane without changing coverage or release workflows. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .github/workflows/build.yml | 490 +++++++++++++++--- README.md | 3 + bindings/js/__test__/borrowed-copy.e2e.ts | 8 +- .../generated-unsafe-companion.e2e.ts | 16 +- bindings/js/__test__/native-completion.e2e.ts | 18 +- bindings/js/scripts/run-codegen.d.mts | 9 + bindings/js/scripts/run-codegen.mjs | 24 + bindings/js/scripts/run-codegen.test.mjs | 72 +++ docs/guides/development/ci.md | 103 ++++ eng/ci/artifact.ps1 | 103 ++++ eng/ci/assert-success.ps1 | 31 ++ eng/ci/classify_changes.py | 110 ++++ eng/ci/merge-runtime-artifacts.ps1 | 26 + eng/ci/requirements.txt | 1 + eng/ci/test_ci.py | 329 ++++++++++++ tests/e2e/codegen.ps1 | 33 ++ tests/e2e/e2e_preparation.tests.ps1 | 31 +- tests/e2e/e2e_test.ps1 | 44 +- tests/e2e/implementation_test.ps1 | 13 +- tests/e2e/prebuilt_codegen.tests.ps1 | 114 ++++ 20 files changed, 1458 insertions(+), 120 deletions(-) create mode 100644 bindings/js/scripts/run-codegen.d.mts create mode 100644 bindings/js/scripts/run-codegen.mjs create mode 100644 bindings/js/scripts/run-codegen.test.mjs create mode 100644 docs/guides/development/ci.md create mode 100644 eng/ci/artifact.ps1 create mode 100644 eng/ci/assert-success.ps1 create mode 100644 eng/ci/classify_changes.py create mode 100644 eng/ci/merge-runtime-artifacts.ps1 create mode 100644 eng/ci/requirements.txt create mode 100644 eng/ci/test_ci.py create mode 100644 tests/e2e/codegen.ps1 create mode 100644 tests/e2e/prebuilt_codegen.tests.ps1 diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 7386681f..e1ed3644 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -10,15 +10,36 @@ on: pull_request: branches: [main] +permissions: + contents: read + jobs: + changes: + runs-on: windows-latest + outputs: + docs_only: ${{ steps.classify.outputs.docs_only }} + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + - uses: actions/setup-python@v5 + with: + python-version: "3.12" + - name: Classify the entire PR diff + id: classify + run: python eng\ci\classify_changes.py + format: + needs: changes runs-on: windows-latest steps: - uses: actions/checkout@v4 - uses: dtolnay/rust-toolchain@stable + if: needs.changes.outputs.docs_only == 'false' with: components: rustfmt - name: Check Rust formatting + if: needs.changes.outputs.docs_only == 'false' shell: pwsh run: | cargo fmt --all -- --check @@ -26,10 +47,26 @@ jobs: Write-Error "Rust formatting failed. Run 'cargo fmt --all' and commit the changes." exit 1 } + - uses: actions/setup-node@v4 + with: + node-version: 24 + - uses: actions/setup-python@v5 + with: + python-version: "3.12" + - name: Test CI scheduling and artifact contracts + shell: pwsh + run: | + $PSNativeCommandUseErrorActionPreference = $true + python -m pip install -r eng\ci\requirements.txt --quiet + python -m unittest discover -s eng\ci -p "test_*.py" -v + node --test bindings\js\scripts\run-codegen.test.mjs + .\tests\e2e\e2e_preparation.tests.ps1 + .\tests\e2e\prebuilt_codegen.tests.ps1 - # Tests - test: - needs: format + # Rust test programs are independent builds, not reusable runtime packages. + test-rust: + if: needs.changes.outputs.docs_only == 'false' + needs: [changes, format] runs-on: windows-latest steps: - uses: actions/checkout@v4 @@ -247,9 +284,33 @@ jobs: - name: Check x86 Classic COM runtime run: cargo check -p jswinrt_rs --target i686-pc-windows-msvc - # E2E tests: winmd → generate → call real WinRT APIs - e2e: - needs: test + # Producers start beside Rust tests. Only current-run, configuration-specific + # payloads are reusable; neither a Cargo target tree nor a test program is shared. + build-codegen-x64: + if: needs.changes.outputs.docs_only == 'false' + needs: [changes, format] + runs-on: windows-latest + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@stable + - name: Build x64 codegen + shell: pwsh + run: | + $PSNativeCommandUseErrorActionPreference = $true + cargo build -p dynwinrt-codegen --release --target x86_64-pc-windows-msvc + New-Item -ItemType Directory artifacts\codegen-x64\payload -Force | Out-Null + Copy-Item target\x86_64-pc-windows-msvc\release\dynwinrt-codegen.exe artifacts\codegen-x64\payload + .\eng\ci\artifact.ps1 -Mode Write -Path artifacts\codegen-x64 -Kind codegen -Architecture x64 + - uses: actions/upload-artifact@v4 + with: + name: ci-codegen-x64 + path: artifacts\codegen-x64 + if-no-files-found: error + retention-days: 7 + + build-bindings-x64: + if: needs.changes.outputs.docs_only == 'false' + needs: [changes, format] runs-on: windows-latest steps: - uses: actions/checkout@v4 @@ -260,6 +321,164 @@ jobs: - uses: actions/setup-python@v5 with: python-version: "3.12" + architecture: x64 + - name: Build production JS binding + working-directory: bindings/js + shell: pwsh + run: | + $PSNativeCommandUseErrorActionPreference = $true + npm install + npx napi build --no-const-enum --platform --release --target x86_64-pc-windows-msvc -o dist + npm run build:entrypoints --silent + node scripts\verify-runtime-artifact.mjs dist + - name: Stage production JS artifact + shell: pwsh + run: | + New-Item -ItemType Directory artifacts\js-x64 -Force | Out-Null + Copy-Item bindings\js\dist artifacts\js-x64\payload -Recurse + .\eng\ci\artifact.ps1 -Mode Write -Path artifacts\js-x64 -Kind js -Architecture x64 + - uses: actions/upload-artifact@v4 + with: + name: ci-js-x64 + path: artifacts\js-x64 + if-no-files-found: error + retention-days: 7 + - name: Build Python binding + working-directory: bindings/py + shell: pwsh + run: | + $PSNativeCommandUseErrorActionPreference = $true + python -m pip install "maturin>=1.11,<2" --quiet + python -m maturin build --quiet --interpreter python --target x86_64-pc-windows-msvc ` + --out ..\..\artifacts\python-x64\payload + ..\..\eng\ci\artifact.ps1 -Mode Write -Path ..\..\artifacts\python-x64 ` + -Kind python -Architecture x64 -Profile dev -PythonAbi cp312 + - uses: actions/upload-artifact@v4 + with: + name: ci-python-x64 + path: artifacts\python-x64 + if-no-files-found: error + retention-days: 7 + + build-js-test-hooks: + if: needs.changes.outputs.docs_only == 'false' + needs: [changes, format] + runs-on: windows-latest + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@stable + - uses: actions/setup-node@v4 + with: + node-version: 24 + - name: Build isolated JS native fixtures + working-directory: bindings/js + shell: pwsh + run: | + $PSNativeCommandUseErrorActionPreference = $true + npm install + npx napi build --no-const-enum --platform --release --target x86_64-pc-windows-msvc --features test-hooks -o dist + npm run build:entrypoints --silent + node scripts\verify-runtime-artifact.mjs dist --test-hooks + - name: Stage test-hooks artifact + shell: pwsh + run: | + New-Item -ItemType Directory artifacts\js-test-hooks-x64 -Force | Out-Null + Copy-Item bindings\js\dist artifacts\js-test-hooks-x64\payload -Recurse + .\eng\ci\artifact.ps1 -Mode Write -Path artifacts\js-test-hooks-x64 ` + -Kind js -Architecture x64 -Features test-hooks + - uses: actions/upload-artifact@v4 + with: + name: ci-js-test-hooks-x64 + path: artifacts\js-test-hooks-x64 + if-no-files-found: error + retention-days: 7 + + build-arm64: + if: needs.changes.outputs.docs_only == 'false' + needs: [changes, format] + runs-on: windows-latest + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@stable + with: + targets: aarch64-pc-windows-msvc + - uses: actions/setup-node@v4 + with: + node-version: 24 + - name: Build ARM64 codegen + shell: pwsh + run: | + $PSNativeCommandUseErrorActionPreference = $true + cargo build -p dynwinrt-codegen --release --target aarch64-pc-windows-msvc + New-Item -ItemType Directory artifacts\codegen-arm64\payload -Force | Out-Null + Copy-Item target\aarch64-pc-windows-msvc\release\dynwinrt-codegen.exe artifacts\codegen-arm64\payload + .\eng\ci\artifact.ps1 -Mode Write -Path artifacts\codegen-arm64 -Kind codegen -Architecture arm64 + - uses: actions/upload-artifact@v4 + with: + name: ci-codegen-arm64 + path: artifacts\codegen-arm64 + if-no-files-found: error + retention-days: 7 + - name: Build production ARM64 JS binding + working-directory: bindings/js + shell: pwsh + run: | + $PSNativeCommandUseErrorActionPreference = $true + npm install + npx napi build --no-const-enum --platform --release --target aarch64-pc-windows-msvc -o dist + npm run build:entrypoints --silent + - name: Stage ARM64 JS artifact + shell: pwsh + run: | + New-Item -ItemType Directory artifacts\js-arm64 -Force | Out-Null + Copy-Item bindings\js\dist artifacts\js-arm64\payload -Recurse + .\eng\ci\artifact.ps1 -Mode Write -Path artifacts\js-arm64 -Kind js -Architecture arm64 + - name: Compile raw union MSVC C oracle for ARM64 + run: cargo test -p jswinrt_rs --features test-hooks --target aarch64-pc-windows-msvc --no-run + - uses: actions/upload-artifact@v4 + with: + name: ci-js-arm64 + path: artifacts\js-arm64 + if-no-files-found: error + retention-days: 7 + + # Production E2E never waits for the ARM64 lane or the Rust test job. + e2e-runtime: + if: needs.changes.outputs.docs_only == 'false' + needs: [changes, build-codegen-x64, build-bindings-x64] + runs-on: windows-latest + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@stable + - uses: actions/setup-node@v4 + with: + node-version: 24 + - uses: actions/setup-python@v5 + with: + python-version: "3.12" + architecture: x64 + - uses: actions/download-artifact@v4 + with: + name: ci-codegen-x64 + path: artifacts\codegen-x64 + - uses: actions/download-artifact@v4 + with: + name: ci-js-x64 + path: artifacts\js-x64 + - uses: actions/download-artifact@v4 + with: + name: ci-python-x64 + path: artifacts\python-x64 + - name: Verify production input artifacts + shell: pwsh + run: | + $PSNativeCommandUseErrorActionPreference = $true + .\eng\ci\artifact.ps1 -Mode Verify -Path artifacts\codegen-x64 -Kind codegen -Architecture x64 + .\eng\ci\artifact.ps1 -Mode Verify -Path artifacts\js-x64 -Kind js -Architecture x64 + .\eng\ci\artifact.ps1 -Mode Verify -Path artifacts\python-x64 -Kind python -Architecture x64 -Profile dev -PythonAbi cp312 + Copy-Item artifacts\js-x64\payload bindings\js\dist -Recurse + node bindings\js\scripts\verify-runtime-artifact.mjs bindings\js\dist + "DYNWINRT_CODEGEN=$((Resolve-Path artifacts\codegen-x64\payload\dynwinrt-codegen.exe).Path)" >> $env:GITHUB_ENV - uses: NuGet/setup-nuget@v2 - name: Install Win32 metadata shell: pwsh @@ -277,36 +496,32 @@ jobs: } "DYNWINRT_WIN32_WINMD=$($winmd.FullName)" >> $env:GITHUB_ENV "DYNWINRT_REQUIRE_WIN32_METADATA=1" >> $env:GITHUB_ENV - - name: Build dynwinrt-codegen - run: cargo build -p dynwinrt-codegen --release - - name: Build JS binding + - name: Install JS test dependencies working-directory: bindings/js - run: | - npm install - npx napi build --no-const-enum --platform --release -o dist - if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } - npm run build:entrypoints --silent - npm install --no-save tsx + run: npm install - name: Test JS binding working-directory: bindings/js run: npm test - - name: Build Python binding + - name: Install prebuilt Python binding + shell: pwsh run: | - cd bindings/py - python -m venv .venv - .venv/Scripts/Activate.ps1 - pip install pytest maturin "mypy>=1.13,<2" "coverage>=7.15,<8" --quiet - maturin build --quiet - pip install (Get-ChildItem ../../target/wheels/*.whl | Sort-Object LastWriteTime -Descending | Select-Object -First 1).FullName --force-reinstall --quiet + $PSNativeCommandUseErrorActionPreference = $true + python -m venv bindings\py\.venv + $python = '.\bindings\py\.venv\Scripts\python.exe' + & $python -m pip install pytest "mypy>=1.13,<2" "coverage>=7.15,<8" --quiet + $wheels = @(Get-ChildItem artifacts\python-x64\payload -Filter *.whl -File) + if ($wheels.Count -ne 1) { throw 'Expected exactly the verified CPython 3.12 x64 wheel' } + & $python -m pip install $wheels[0].FullName --no-deps --no-index --quiet - name: Test Python binding run: | .\bindings\py\.venv\Scripts\python.exe -m pytest bindings\py\tests -q + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } .\bindings\py\.venv\Scripts\python.exe -m mypy.stubtest dynwinrt --allowlist bindings\py\stubtest_allowlist.txt --ignore-disjoint-bases - name: Test generated Python long paths run: | .\eng\release\python\test_generated_python_long_paths.ps1 ` -Python .\bindings\py\.venv\Scripts\python.exe ` - -Codegen .\target\release\dynwinrt-codegen.exe + -Codegen $env:DYNWINRT_CODEGEN - name: Test generated implementation symbol identities shell: pwsh run: | @@ -314,7 +529,7 @@ jobs: $env:DYNWINRT_REQUIRE_IMPLEMENTATION_RUNTIME = '1' cargo test -p dynwinrt-codegen --test implementation_naming_test - name: Run E2E tests - run: .\tests\e2e\e2e_test.ps1 -SkipBuild + run: .\tests\e2e\e2e_test.ps1 -SkipBuild -Codegen $env:DYNWINRT_CODEGEN # This optional-SDK behavioral smoke is separate from generated coverage # totals. The receiver/GIL regressions also run in instrumented core and # binding tests; no WinAppSDK runtime bootstrap or UI loop is needed here. @@ -340,93 +555,244 @@ jobs: -Filter Windows.winmd -File -Recurse | Sort-Object FullName -Descending | Select-Object -First 1 if (-not $windows) { throw 'Windows SDK metadata is required for the dispatcher smoke' } $output = Join-Path $PWD 'artifacts\dispatcher-implementation-smoke' - .\target\release\dynwinrt-codegen.exe generate ` + & $env:DYNWINRT_CODEGEN generate ` --winmd (Join-Path $metadata 'Microsoft.UI.winmd') --ref $windows.FullName ` --namespace Microsoft.UI.Dispatching --class-name DispatcherQueue ` --lang py --output $output if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } .\bindings\py\.venv\Scripts\python.exe .\tests\e2e\runners\dispatcher_implementation_py.py --generated $output + + e2e-native: + if: needs.changes.outputs.docs_only == 'false' + needs: [changes, build-codegen-x64, build-js-test-hooks] + runs-on: windows-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 24 + - uses: actions/download-artifact@v4 + with: + name: ci-codegen-x64 + path: artifacts\codegen-x64 + - uses: actions/download-artifact@v4 + with: + name: ci-js-test-hooks-x64 + path: artifacts\js-test-hooks-x64 + - name: Verify isolated native fixture artifacts + shell: pwsh + run: | + $PSNativeCommandUseErrorActionPreference = $true + .\eng\ci\artifact.ps1 -Mode Verify -Path artifacts\codegen-x64 -Kind codegen -Architecture x64 + .\eng\ci\artifact.ps1 -Mode Verify -Path artifacts\js-test-hooks-x64 -Kind js -Architecture x64 -Features test-hooks + Copy-Item artifacts\js-test-hooks-x64\payload bindings\js\dist -Recurse + node bindings\js\scripts\verify-runtime-artifact.mjs bindings\js\dist --test-hooks + "DYNWINRT_CODEGEN=$((Resolve-Path artifacts\codegen-x64\payload\dynwinrt-codegen.exe).Path)" >> $env:GITHUB_ENV + - name: Install JS test dependencies + working-directory: bindings/js + run: npm install + - uses: NuGet/setup-nuget@v2 + - name: Install Win32 metadata + shell: pwsh + run: | + $PSNativeCommandUseErrorActionPreference = $true + $root = Join-Path $env:RUNNER_TEMP 'win32metadata' + nuget install Microsoft.Windows.SDK.Win32Metadata ` + -Version 71.0.14-preview -OutputDirectory $root -DirectDownload -NonInteractive + $winmd = Get-ChildItem $root -Filter Windows.Win32.winmd -File -Recurse | Select-Object -First 1 + if (-not $winmd) { throw 'Microsoft.Windows.SDK.Win32Metadata did not contain Windows.Win32.winmd' } + "DYNWINRT_WIN32_WINMD=$($winmd.FullName)" >> $env:GITHUB_ENV + "DYNWINRT_REQUIRE_WIN32_METADATA=1" >> $env:GITHUB_ENV + # These execute the same tests as the developer npm scripts, but must not + # run their build:test-hooks prefixes over the downloaded immutable inputs. - name: Test JS TSFN lifecycle and queue handling working-directory: bindings/js - run: npm run test:tsfn + run: npx --no-install ava __test__/tsfn.spec.ts - name: Test actual generated unsafe COM companion working-directory: bindings/js - run: npm run test:generated-unsafe + run: npx --no-install ava __test__/generated-unsafe-companion.e2e.ts - name: Test metadata-driven native COM one-shot completion working-directory: bindings/js - run: npm run test:native-completion + run: npx --no-install ava __test__/native-completion.e2e.ts - name: Test metadata-driven COM borrowed copies working-directory: bindings/js - run: npm run test:borrowed-copy + run: npx --no-install ava __test__/borrowed-copy.e2e.ts - name: Test Win32 failed-cleanup recovery working-directory: bindings/js run: node --expose-gc __test__\fixtures\win32-cleanup-errors.cjs - # dynwinrt-codegen (x64 + arm64) + # Stable check identities also complete on intentional documentation-only skips. + test: + if: ${{ always() }} + needs: [changes, format, test-rust] + runs-on: windows-latest + steps: + - uses: actions/checkout@v4 + - name: Require Rust validation + env: + NEEDS: ${{ toJSON(needs) }} + REQUIRED_JOBS: changes,format,test-rust + DOCS_ONLY: ${{ needs.changes.outputs.docs_only }} + DOCS_SKIPPABLE_JOBS: test-rust + run: | + .\eng\ci\assert-success.ps1 -NeedsJson $env:NEEDS -RequiredJobs ($env:REQUIRED_JOBS -split ',') ` + -DocsOnly $env:DOCS_ONLY -SkippableJobs ($env:DOCS_SKIPPABLE_JOBS -split ',') + + e2e: + if: ${{ always() }} + needs: + [ + changes, + format, + test, + build-codegen-x64, + build-bindings-x64, + build-js-test-hooks, + e2e-runtime, + e2e-native, + ] + runs-on: windows-latest + steps: + - uses: actions/checkout@v4 + - name: Require all E2E lanes + env: + NEEDS: ${{ toJSON(needs) }} + REQUIRED_JOBS: changes,format,test,build-codegen-x64,build-bindings-x64,build-js-test-hooks,e2e-runtime,e2e-native + DOCS_ONLY: ${{ needs.changes.outputs.docs_only }} + DOCS_SKIPPABLE_JOBS: build-codegen-x64,build-bindings-x64,build-js-test-hooks,e2e-runtime,e2e-native + run: | + .\eng\ci\assert-success.ps1 -NeedsJson $env:NEEDS -RequiredJobs ($env:REQUIRED_JOBS -split ',') ` + -DocsOnly $env:DOCS_ONLY -SkippableJobs ($env:DOCS_SKIPPABLE_JOBS -split ',') + + # Only these gated assembly jobs publish the existing release-ready names. dynwinrt-codegen: - needs: test + if: ${{ always() }} + needs: [changes, test, e2e, build-codegen-x64, build-arm64] runs-on: windows-latest steps: - uses: actions/checkout@v4 - - uses: dtolnay/rust-toolchain@stable - with: - targets: aarch64-pc-windows-msvc - - name: Build x64 + - name: Require all validation + env: + NEEDS: ${{ toJSON(needs) }} + REQUIRED_JOBS: changes,test,e2e,build-codegen-x64,build-arm64 + DOCS_ONLY: ${{ needs.changes.outputs.docs_only }} + DOCS_SKIPPABLE_JOBS: build-codegen-x64,build-arm64 run: | - cargo build -p dynwinrt-codegen --release - mkdir -p tools/dynwinrt-codegen/npm/bin/x64 - cp target/release/dynwinrt-codegen.exe tools/dynwinrt-codegen/npm/bin/x64/ - - name: Build arm64 + .\eng\ci\assert-success.ps1 -NeedsJson $env:NEEDS -RequiredJobs ($env:REQUIRED_JOBS -split ',') ` + -DocsOnly $env:DOCS_ONLY -SkippableJobs ($env:DOCS_SKIPPABLE_JOBS -split ',') + - uses: actions/download-artifact@v4 + if: needs.changes.outputs.docs_only == 'false' + with: + name: ci-codegen-x64 + path: artifacts\codegen-x64 + - uses: actions/download-artifact@v4 + if: needs.changes.outputs.docs_only == 'false' + with: + name: ci-codegen-arm64 + path: artifacts\codegen-arm64 + - name: Assemble verified codegen package + if: needs.changes.outputs.docs_only == 'false' + shell: pwsh run: | - cargo build -p dynwinrt-codegen --release --target aarch64-pc-windows-msvc - mkdir -p tools/dynwinrt-codegen/npm/bin/arm64 - cp target/aarch64-pc-windows-msvc/release/dynwinrt-codegen.exe tools/dynwinrt-codegen/npm/bin/arm64/ + .\eng\ci\artifact.ps1 -Mode Verify -Path artifacts\codegen-x64 -Kind codegen -Architecture x64 + .\eng\ci\artifact.ps1 -Mode Verify -Path artifacts\codegen-arm64 -Kind codegen -Architecture arm64 + foreach ($arch in @('x64', 'arm64')) { + New-Item -ItemType Directory "tools\dynwinrt-codegen\npm\bin\$arch" -Force | Out-Null + Copy-Item "artifacts\codegen-$arch\payload\dynwinrt-codegen.exe" "tools\dynwinrt-codegen\npm\bin\$arch" + } - uses: actions/upload-artifact@v4 + if: needs.changes.outputs.docs_only == 'false' with: name: dynwinrt-codegen path: tools/dynwinrt-codegen/npm/ + if-no-files-found: error - # dynwinrt (x64 + arm64 in one job) dynwinrt: - needs: test + if: ${{ always() }} + needs: [changes, test, e2e, build-bindings-x64, build-arm64] runs-on: windows-latest steps: - uses: actions/checkout@v4 - - uses: dtolnay/rust-toolchain@stable - with: - targets: aarch64-pc-windows-msvc + - name: Require all validation + env: + NEEDS: ${{ toJSON(needs) }} + REQUIRED_JOBS: changes,test,e2e,build-bindings-x64,build-arm64 + DOCS_ONLY: ${{ needs.changes.outputs.docs_only }} + DOCS_SKIPPABLE_JOBS: build-bindings-x64,build-arm64 + run: | + .\eng\ci\assert-success.ps1 -NeedsJson $env:NEEDS -RequiredJobs ($env:REQUIRED_JOBS -split ',') ` + -DocsOnly $env:DOCS_ONLY -SkippableJobs ($env:DOCS_SKIPPABLE_JOBS -split ',') - uses: actions/setup-node@v4 + if: needs.changes.outputs.docs_only == 'false' with: node-version: 24 - - name: Install dependencies + - uses: actions/download-artifact@v4 + if: needs.changes.outputs.docs_only == 'false' + with: + name: ci-js-x64 + path: artifacts\js-x64 + - uses: actions/download-artifact@v4 + if: needs.changes.outputs.docs_only == 'false' + with: + name: ci-js-arm64 + path: artifacts\js-arm64 + - name: Assemble matching production runtime sidecars + if: needs.changes.outputs.docs_only == 'false' + run: .\eng\ci\merge-runtime-artifacts.ps1 -X64 artifacts\js-x64 -Arm64 artifacts\js-arm64 -Output bindings\js\dist + - name: Install import test dependencies + if: needs.changes.outputs.docs_only == 'false' working-directory: bindings/js run: npm install - - name: Compile raw union MSVC C oracle for ARM64 - run: cargo test -p jswinrt_rs --features test-hooks --target aarch64-pc-windows-msvc --no-run - - name: Build x64 - working-directory: bindings/js - run: | - npx napi build --no-const-enum --platform --release -o dist - if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } - npm run build:entrypoints --silent - - name: Build arm64 - working-directory: bindings/js - run: | - npx napi build --no-const-enum --platform --release --target aarch64-pc-windows-msvc -o dist - if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } - npm run build:entrypoints --silent - name: Check production native imports + if: needs.changes.outputs.docs_only == 'false' working-directory: bindings/js run: npm run test:imports + - name: Verify assembled JS runtime artifact + if: needs.changes.outputs.docs_only == 'false' + run: node .\bindings\js\scripts\verify-runtime-artifact.mjs .\bindings\js\dist - uses: actions/upload-artifact@v4 + if: needs.changes.outputs.docs_only == 'false' with: name: dynwinrt path: bindings/js/dist/ if-no-files-found: error - uses: actions/download-artifact@v4 + if: needs.changes.outputs.docs_only == 'false' with: name: dynwinrt path: ${{ runner.temp }}\dynwinrt-artifact - name: Verify downloaded JS runtime artifact + if: needs.changes.outputs.docs_only == 'false' shell: pwsh run: node .\bindings\js\scripts\verify-runtime-artifact.mjs "$env:RUNNER_TEMP\dynwinrt-artifact" + + ci-success: + if: ${{ always() }} + needs: + [ + changes, + format, + test-rust, + test, + build-codegen-x64, + build-bindings-x64, + build-js-test-hooks, + build-arm64, + e2e-runtime, + e2e-native, + e2e, + dynwinrt, + dynwinrt-codegen, + ] + runs-on: windows-latest + steps: + - uses: actions/checkout@v4 + - name: Require every Build job + env: + NEEDS: ${{ toJSON(needs) }} + REQUIRED_JOBS: changes,format,test-rust,test,build-codegen-x64,build-bindings-x64,build-js-test-hooks,build-arm64,e2e-runtime,e2e-native,e2e,dynwinrt,dynwinrt-codegen + DOCS_ONLY: ${{ needs.changes.outputs.docs_only }} + DOCS_SKIPPABLE_JOBS: test-rust,build-codegen-x64,build-bindings-x64,build-js-test-hooks,build-arm64,e2e-runtime,e2e-native + run: | + .\eng\ci\assert-success.ps1 -NeedsJson $env:NEEDS -RequiredJobs ($env:REQUIRED_JOBS -split ',') ` + -DocsOnly $env:DOCS_ONLY -SkippableJobs ($env:DOCS_SKIPPABLE_JOBS -split ',') diff --git a/README.md b/README.md index b8b8f12a..b54a8abb 100644 --- a/README.md +++ b/README.md @@ -189,6 +189,9 @@ builds, test suites, and contribution guidelines. ## Contributing +See the [Build CI guide](docs/guides/development/ci.md) for parallel validation, +artifact reuse, documentation-only PR checks, and running E2E with a prebuilt generator. + This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit . When you submit a pull request, a CLA bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., status check, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA. diff --git a/bindings/js/__test__/borrowed-copy.e2e.ts b/bindings/js/__test__/borrowed-copy.e2e.ts index 9858dce8..29a9663c 100644 --- a/bindings/js/__test__/borrowed-copy.e2e.ts +++ b/bindings/js/__test__/borrowed-copy.e2e.ts @@ -5,6 +5,7 @@ import test from 'ava' import { spawnSync } from 'node:child_process' import { mkdirSync, rmSync, symlinkSync, writeFileSync } from 'node:fs' import { join, resolve } from 'node:path' +import { runCodegen } from '../scripts/run-codegen.mjs' const packageRoot = resolve(process.cwd()) const repositoryRoot = resolve(packageRoot, '..', '..') @@ -15,11 +16,6 @@ test.before((t) => { t.truthy(winmd, 'Pinned DYNWINRT_WIN32_WINMD is required') rmSync(output, { recursive: true, force: true }) const args = [ - 'run', - '--quiet', - '-p', - 'dynwinrt-codegen', - '--', 'generate', '--winmd', winmd!, @@ -29,7 +25,7 @@ test.before((t) => { output, ] for (const extra of [['--dry-run'], []]) { - const generated = spawnSync('cargo', [...args, ...extra], { + const generated = runCodegen([...args, ...extra], { cwd: repositoryRoot, encoding: 'utf8', windowsHide: true, diff --git a/bindings/js/__test__/generated-unsafe-companion.e2e.ts b/bindings/js/__test__/generated-unsafe-companion.e2e.ts index 6505a9ca..c8beb16a 100644 --- a/bindings/js/__test__/generated-unsafe-companion.e2e.ts +++ b/bindings/js/__test__/generated-unsafe-companion.e2e.ts @@ -6,6 +6,7 @@ import { spawnSync } from 'node:child_process' import { lstatSync, readFileSync, readlinkSync, rmSync, mkdirSync, mkdtempSync, symlinkSync, writeFileSync } from 'node:fs' import { basename, dirname, join, resolve } from 'node:path' import { pathToFileURL } from 'node:url' +import { runCodegen } from '../scripts/run-codegen.mjs' test.serial('generated IUIAutomation unsafe companion parses and registers without native calls', (t) => { const winmd = process.env.DYNWINRT_WIN32_WINMD @@ -17,14 +18,8 @@ test.serial('generated IUIAutomation unsafe companion parses and registers witho ) try { - const generation = spawnSync( - 'cargo', + const generation = runCodegen( [ - 'run', - '--quiet', - '-p', - 'dynwinrt-codegen', - '--', 'generate', '--winmd', winmd!, @@ -141,11 +136,6 @@ test.serial('generated safe COM and unsafe WinML companions preserve exact contr try { const generationArgs = [ - 'run', - '--quiet', - '-p', - 'dynwinrt-codegen', - '--', 'generate', '--winmd', winmd!, @@ -155,7 +145,7 @@ test.serial('generated safe COM and unsafe WinML companions preserve exact contr output, ] const runGeneration = (extraEnv: NodeJS.ProcessEnv = {}) => - spawnSync('cargo', generationArgs, { + runCodegen(generationArgs, { cwd: repositoryRoot, encoding: 'utf8', env: { ...process.env, DYNWINRT_CODEGEN_TEST_STRATEGY_RUNTIME: '1', ...extraEnv }, diff --git a/bindings/js/__test__/native-completion.e2e.ts b/bindings/js/__test__/native-completion.e2e.ts index 3a8dddb6..6e88dfd6 100644 --- a/bindings/js/__test__/native-completion.e2e.ts +++ b/bindings/js/__test__/native-completion.e2e.ts @@ -5,6 +5,7 @@ import test from 'ava' import { spawnSync } from 'node:child_process' import { mkdirSync, rmSync, symlinkSync, writeFileSync } from 'node:fs' import { join, resolve } from 'node:path' +import { runCodegen } from '../scripts/run-codegen.mjs' const packageRoot = resolve(process.cwd()) const repositoryRoot = resolve(packageRoot, '..', '..') @@ -17,11 +18,6 @@ test.before((t) => { t.truthy(winmd, 'DYNWINRT_WIN32_WINMD is required for exact native-completion generation') rmSync(output, { recursive: true, force: true }) const args = [ - 'run', - '--quiet', - '-p', - 'dynwinrt-codegen', - '--', 'generate', '--winmd', winmd!, @@ -30,28 +26,22 @@ test.before((t) => { '--output', output, ] - const dryRun = spawnSync('cargo', [...args, '--dry-run'], { + const dryRun = runCodegen([...args, '--dry-run'], { cwd: repositoryRoot, encoding: 'utf8', windowsHide: true, }) t.is(dryRun.status, 0, dryRun.stderr) t.regex(dryRun.stdout, /Would generate ActivateAudioInterfaceAsync/) - const generation = spawnSync('cargo', args, { + const generation = runCodegen(args, { cwd: repositoryRoot, encoding: 'utf8', windowsHide: true, }) t.is(generation.status, 0, generation.stderr) if (process.env.DYNWINRT_TEST_AUDIO_RENDER === '1') { - const renderDevice = spawnSync( - 'cargo', + const renderDevice = runCodegen( [ - 'run', - '--quiet', - '-p', - 'dynwinrt-codegen', - '--', 'generate', '--namespace', 'Windows.Media.Devices', diff --git a/bindings/js/scripts/run-codegen.d.mts b/bindings/js/scripts/run-codegen.d.mts new file mode 100644 index 00000000..c9b74066 --- /dev/null +++ b/bindings/js/scripts/run-codegen.d.mts @@ -0,0 +1,9 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import type { SpawnSyncOptionsWithStringEncoding, SpawnSyncReturns } from 'node:child_process' + +export declare function runCodegen( + args: string[], + options: SpawnSyncOptionsWithStringEncoding, +): SpawnSyncReturns diff --git a/bindings/js/scripts/run-codegen.mjs b/bindings/js/scripts/run-codegen.mjs new file mode 100644 index 00000000..96c53d0b --- /dev/null +++ b/bindings/js/scripts/run-codegen.mjs @@ -0,0 +1,24 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { spawnSync } from 'node:child_process' +import { statSync } from 'node:fs' +import { resolve } from 'node:path' + +/** + * An explicit artifact path must never fall back to a local Cargo build. + * @param {string[]} args + * @param {import('node:child_process').SpawnSyncOptionsWithStringEncoding} options + */ +export function runCodegen(args, options) { + const codegen = (options.env ?? process.env).DYNWINRT_CODEGEN + if (codegen !== undefined) { + if (!codegen.trim()) throw new Error('DYNWINRT_CODEGEN must name a prebuilt dynwinrt-codegen executable') + const executable = resolve(options.cwd?.toString() ?? process.cwd(), codegen) + if (!statSync(executable).isFile()) throw new Error(`Prebuilt dynwinrt-codegen is not a file: ${executable}`) + const result = spawnSync(executable, args, options) + if (result.error) throw result.error + return result + } + return spawnSync('cargo', ['run', '--quiet', '-p', 'dynwinrt-codegen', '--', ...args], options) +} diff --git a/bindings/js/scripts/run-codegen.test.mjs b/bindings/js/scripts/run-codegen.test.mjs new file mode 100644 index 00000000..b2c4d84d --- /dev/null +++ b/bindings/js/scripts/run-codegen.test.mjs @@ -0,0 +1,72 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import assert from 'node:assert/strict' +import childProcess from 'node:child_process' +import { mkdtempSync, rmSync } from 'node:fs' +import { syncBuiltinESMExports } from 'node:module' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { test } from 'node:test' +import { runCodegen } from './run-codegen.mjs' + +test('prebuilt invocation executes the selected file, arguments and environment without Cargo', () => { + const env = { ...process.env, DYNWINRT_CODEGEN: process.execPath, CODEGEN_SENTINEL: 'forwarded' } + const result = runCodegen(['-e', 'console.log(process.env.CODEGEN_SENTINEL); process.exit(23)'], { + encoding: 'utf8', + env, + windowsHide: true, + }) + assert.equal(result.status, 23) + assert.equal(result.stdout.trim(), 'forwarded') +}) + +test('an invalid executable reports its launch error without trying Cargo', (t) => { + const calls = [] + const error = new Error('not a valid executable') + t.mock.method(childProcess, 'spawnSync', (...args) => { + calls.push(args) + return { error, status: null, stdout: null, stderr: null } + }) + syncBuiltinESMExports() + try { + assert.throws( + () => runCodegen(['generate'], { encoding: 'utf8', env: { DYNWINRT_CODEGEN: process.execPath } }), + (actual) => actual === error, + ) + assert.equal(calls.length, 1) + assert.equal(calls[0][0], process.execPath) + } finally { + t.mock.restoreAll() + syncBuiltinESMExports() + } +}) + +test('invalid explicit paths never fall back; omission retains the developer Cargo command', (t) => { + const directory = mkdtempSync(join(tmpdir(), 'dynwinrt-codegen-selection-')) + const calls = [] + t.mock.method(childProcess, 'spawnSync', (...args) => { + calls.push(args) + return { status: 31, stdout: '', stderr: 'cargo boundary' } + }) + syncBuiltinESMExports() + try { + for (const path of ['', ' ', directory, join(directory, 'missing.exe')]) { + assert.throws(() => runCodegen(['generate'], { encoding: 'utf8', env: { DYNWINRT_CODEGEN: path } })) + } + assert.deepEqual(calls, []) + const options = { encoding: 'utf8', env: {}, cwd: directory } + assert.equal(runCodegen(['generate', '--output', 'a path with spaces'], options).status, 31) + assert.deepEqual(calls, [ + [ + 'cargo', + ['run', '--quiet', '-p', 'dynwinrt-codegen', '--', 'generate', '--output', 'a path with spaces'], + options, + ], + ]) + } finally { + t.mock.restoreAll() + syncBuiltinESMExports() + rmSync(directory, { recursive: true, force: true }) + } +}) diff --git a/docs/guides/development/ci.md b/docs/guides/development/ci.md new file mode 100644 index 00000000..2ed5bb29 --- /dev/null +++ b/docs/guides/development/ci.md @@ -0,0 +1,103 @@ +# Build CI + +The `Build` workflow in `.github/workflows/build.yml` runs independent Rust +validation and native package builds in parallel. It does not change the +shipping Cargo release profile, coverage instrumentation, or the separate +Python release matrix. + +## Scheduling and artifacts + +After change classification and lightweight checks, full validation starts +these lanes without waiting for the Rust tests: + +| Job | Responsibility | +| --------------------- | ---------------------------------------------------------------------------------------------------------- | +| `test-rust` | Existing Rust unit, ABI, codegen, census, determinism, cleanup and live i686 checks | +| `build-codegen-x64` | Release x64 generator | +| `build-bindings-x64` | Production release x64 JS distribution and CPython 3.12 x64 development-profile wheel | +| `build-js-test-hooks` | Separate release x64 JS distribution with native test fixtures | +| `build-arm64` | Release ARM64 generator/runtime and the ARM64 C-oracle compile check | +| `e2e-runtime` | Production JS/Python tests, generated WinRT/COM/Win32/implementation E2E, long paths, and dispatcher smoke | +| `e2e-native` | TSFN, generated unsafe COM, native completion, borrowed copies, and Win32 cleanup fixtures | + +The two E2E consumers depend only on their x64 producers, not the ARM64 lane or +Rust tests. The original `test` and `e2e` check names aggregate their respective +validation lanes; the `e2e` aggregate retains its Rust-test prerequisite without +delaying either E2E consumer. `dynwinrt` and `dynwinrt-codegen` assemble the original +dual-architecture final artifacts only after Rust, E2E and the relevant builds +succeed. `ci-success` checks every job result, including final artifact +verification. Failure, cancellation, a missing result or an unexpected skip +fails these gates. + +Intermediate `ci-*` artifacts are inputs, **not release-ready packages**. +Downloads use the current workflow run. Each input includes a file-hash manifest +with the commit, run, package version, architecture, Cargo profile, feature set +and, for wheels, CPython ABI. Consumers verify it before using the payload. +The full JS distribution is transferred, including declarations and COM/Win32 +sidecars. Assembly requires identical architecture-independent files and keeps +both native binaries; it never overlays test-hook files onto production. + +Rust test executables still need their own `cargo test` builds. In particular, +the runtime-backed `implementation_naming_test` is not replaced by a generator +executable. Coverage binaries and the separate Python release workflow's +packaging configurations are not shared with production. + +## Documentation-only pull requests + +Only pull requests proven to change explanatory documents in the exact allowlist +in `eng/ci/classify_changes.py` take the lightweight path. The list includes the +root README, reviewed usage/architecture guides, and existing sample READMEs. +It does not include packaged READMEs, `docs/status`, generated reports, schemas, +tests, scripts, workflows, sample code/configuration, or unknown paths. + +Classification compares the PR merge base to its head using complete Git +history, not just the latest commit. Both old and new rename paths must qualify; +allowlisted deletions are documentation changes too. An empty diff uses full +validation. Invalid or unavailable history fails classification rather than +guessing that the change is documentation-only. + +The lightweight path runs the scheduling, artifact and prebuilt-selection +regressions without compiling native code. Stable check names still run and +validate the explicitly expected heavy-job skips; no package artifact is +created. Pushes to `main` and version tags always use full validation. The +workflow is not hidden behind a top-level path filter. + +## Using a prebuilt generator locally + +Ordinary developer commands are unchanged: omitting a generator override uses +Cargo with the selected `-CargoProfile` and `-CargoTarget`. `-SkipBuild` alone +skips initial native builds, but still permits the existing Cargo generation +path. To prohibit generator rebuilds, supply a real executable explicitly: + +```powershell +.\tests\e2e\e2e_test.ps1 -SkipBuild ` + -Codegen C:\artifacts\dynwinrt-codegen.exe + +.\tests\e2e\e2e_test.ps1 -SkipBuild -Suite implementations ` + -Codegen C:\artifacts\dynwinrt-codegen.exe -Lang py,ts +``` + +`DYNWINRT_CODEGEN` provides the same default for both PowerShell entrypoints and +the JavaScript generated-unsafe, native-completion and borrowed-copy tests. +An explicit `-Codegen` takes precedence. Missing/invalid explicit files fail; +they never silently fall back to Cargo or a stale local binary. + +Binding artifacts must already be installed when using `-SkipBuild`: the full +matching JS distribution in `bindings\js\dist`, and a compatible wheel in the +selected Python environment. The JS fixture npm scripts retain their local +`build:test-hooks` behavior. CI instead runs their AVA tests directly against a +verified, separately downloaded test-hooks distribution. + +Run the lightweight regressions with: + +```powershell +python -m pip install -r eng\ci\requirements.txt +python -m unittest discover -s eng\ci -p "test_*.py" -v +node --test bindings\js\scripts\run-codegen.test.mjs +.\tests\e2e\e2e_preparation.tests.ps1 +.\tests\e2e\prebuilt_codegen.tests.ps1 +``` + +Parallelism removes the old Rust-test barrier and duplicate release builds; +actual hosted run times still depend on runner capacity and artifact transfer. +Measure completed runs before treating a wall-clock improvement as established. diff --git a/eng/ci/artifact.ps1 b/eng/ci/artifact.ps1 new file mode 100644 index 00000000..010ff8e9 --- /dev/null +++ b/eng/ci/artifact.ps1 @@ -0,0 +1,103 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +param( + [Parameter(Mandatory)][ValidateSet("Write", "Verify")][string]$Mode, + [Parameter(Mandatory)][string]$Path, + [Parameter(Mandatory)][ValidateSet("codegen", "js", "python")][string]$Kind, + [Parameter(Mandatory)][ValidateSet("x64", "arm64")][string]$Architecture, + [ValidateSet("release", "dev")][string]$Profile = "release", + [ValidateSet("production", "test-hooks")][string]$Features = "production", + [string]$PythonAbi +) + +$ErrorActionPreference = "Stop" +$repo = (Resolve-Path (Join-Path $PSScriptRoot "..\..")).Path +if (-not $env:GITHUB_SHA -or -not $env:GITHUB_RUN_ID) { + throw "Artifact identity requires GITHUB_SHA and GITHUB_RUN_ID." +} +$payload = (Get-Item -LiteralPath (Join-Path $Path "payload")).FullName +if (-not (Test-Path -LiteralPath $payload -PathType Container)) { + throw "Missing artifact payload directory: $payload" +} +$manifestPath = Join-Path $Path "manifest.json" +$version = if ($Kind -eq "js") { + (Get-Content -LiteralPath (Join-Path $repo "bindings\js\package.json") -Raw | ConvertFrom-Json).version +} else { + $cargo = if ($Kind -eq "codegen") { "tools\dynwinrt-codegen\Cargo.toml" } else { "bindings\py\Cargo.toml" } + $content = Get-Content -LiteralPath (Join-Path $repo $cargo) -Raw + $package = [regex]::Match($content, '(?ms)^\[package\]\r?\n(.*?)(?=^\[|\z)').Groups[1].Value + $versions = [regex]::Matches($package, '(?m)^version = "([^"]+)"\r?$') + if ($versions.Count -ne 1) { throw "Expected one package version in $cargo" } + $versions[0].Groups[1].Value +} +$target = if ($Architecture -eq "x64") { "x86_64-pc-windows-msvc" } else { "aarch64-pc-windows-msvc" } +$identity = [ordered]@{ + schema = 1 + commit = $env:GITHUB_SHA + run = $env:GITHUB_RUN_ID + kind = $Kind + version = $version + target = $target + profile = $Profile + features = $Features + pythonAbi = $PythonAbi +} +$files = [ordered]@{} +foreach ($file in (Get-ChildItem -LiteralPath $payload -File -Recurse | Sort-Object FullName)) { + $relative = [IO.Path]::GetRelativePath($payload, $file.FullName).Replace("\", "/") + $files[$relative] = (Get-FileHash -LiteralPath $file.FullName -Algorithm SHA256).Hash +} +if ($files.Count -eq 0) { throw "Artifact payload is empty: $payload" } + +if ($Kind -eq "python") { + if ($Features -ne "production" -or $PythonAbi -notmatch '^cp3\d+$') { + throw "Python artifacts require a production wheel and an explicit CPython ABI." + } + $platform = if ($Architecture -eq "x64") { "win_amd64" } else { "win_arm64" } + $wheel = "dynwinrt-$version-$PythonAbi-$PythonAbi-$platform.whl" + if ($files.Count -ne 1 -or -not $files.Contains($wheel)) { + throw "Expected exactly the runtime wheel $wheel" + } +} else { + if ($PythonAbi) { throw "Only Python artifacts may specify a Python ABI." } + $native = if ($Kind -eq "codegen") { "dynwinrt-codegen.exe" } else { "dynwinrt.win32-$Architecture-msvc.node" } + if (-not $files.Contains($native)) { throw "Missing $native in $payload" } + $nativeFiles = @($files.Keys | Where-Object { $_ -match '\.(exe|node)$' }) + if ($nativeFiles.Count -ne 1) { throw "Expected one native binary in $payload" } + if ($Kind -eq "codegen" -and ($Features -ne "production" -or $files.Count -ne 1)) { + throw "Codegen artifacts must contain only the production executable." + } + $bytes = [IO.File]::ReadAllBytes((Join-Path $payload $native)) + if ($bytes.Length -lt 64 -or [BitConverter]::ToUInt16($bytes, 0) -ne 0x5a4d) { + throw "Invalid native PE artifact: $native" + } + $pe = [BitConverter]::ToInt32($bytes, 0x3c) + $machine = if ($Architecture -eq "x64") { 0x8664 } else { 0xaa64 } + if ($pe -lt 64 -or $pe -gt $bytes.Length - 24 -or + [BitConverter]::ToUInt32($bytes, $pe) -ne 0x4550 -or + [BitConverter]::ToUInt16($bytes, $pe + 4) -ne $machine) { + throw "Invalid PE architecture for $native (expected $Architecture)" + } +} + +if ($Mode -eq "Write") { + if (Test-Path -LiteralPath $manifestPath) { throw "Artifact manifest already exists: $manifestPath" } + $identity.files = $files + $identity | ConvertTo-Json -Depth 5 | Set-Content -LiteralPath $manifestPath -Encoding utf8 +} else { + $manifest = Get-Content -LiteralPath $manifestPath -Raw | ConvertFrom-Json -AsHashtable + foreach ($key in $identity.Keys) { + if (-not $manifest.ContainsKey($key) -or $manifest[$key] -cne $identity[$key]) { + throw "Artifact $key mismatch in $manifestPath" + } + } + if ($manifest.files -isnot [System.Collections.IDictionary] -or + @(Compare-Object @($files.Keys | Sort-Object) @($manifest.files.Keys | Sort-Object)).Count) { + throw "Artifact file set mismatch in $manifestPath" + } + foreach ($file in $files.Keys) { + if ($manifest.files[$file] -cne $files[$file]) { throw "Artifact SHA256 mismatch: $file" } + } +} +Write-Host "$Mode verified $Kind $Architecture $Profile $Features ($($files.Count) files, $($identity.commit))" diff --git a/eng/ci/assert-success.ps1 b/eng/ci/assert-success.ps1 new file mode 100644 index 00000000..b45a06ba --- /dev/null +++ b/eng/ci/assert-success.ps1 @@ -0,0 +1,31 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +param( + [Parameter(Mandatory)][string]$NeedsJson, + [Parameter(Mandatory)][string[]]$RequiredJobs, + [ValidateSet("true", "false")][string]$DocsOnly = "false", + [string[]]$SkippableJobs = @() +) + +$ErrorActionPreference = "Stop" +$needs = $NeedsJson | ConvertFrom-Json -AsHashtable +if ($needs -isnot [System.Collections.IDictionary] -or $RequiredJobs.Count -eq 0) { + throw "A success gate requires named job results." +} +if (@(Compare-Object @($needs.Keys | Sort-Object) @($RequiredJobs | Sort-Object)).Count) { + throw "Success gate dependencies do not match the required jobs." +} +if ($needs.changes.result -ne "success" -or $needs.changes.outputs.docs_only -cne $DocsOnly) { + throw "A success gate requires successful, matching change classification." +} +if (@($SkippableJobs | Where-Object { $_ -notin $RequiredJobs -or $_ -eq "changes" }).Count) { + throw "Only declared heavy dependencies may be skipped." +} +foreach ($job in $RequiredJobs) { + $expected = if ($DocsOnly -eq "true" -and $job -in $SkippableJobs) { "skipped" } else { "success" } + if ($needs[$job].result -ne $expected) { + throw "Required job '$job' has result '$($needs[$job].result)'; expected '$expected'." + } +} +Write-Host "All required jobs have the expected results (docs-only: $DocsOnly): $($RequiredJobs -join ', ')" diff --git a/eng/ci/classify_changes.py b/eng/ci/classify_changes.py new file mode 100644 index 00000000..ef58e930 --- /dev/null +++ b/eng/ci/classify_changes.py @@ -0,0 +1,110 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +"""Conservative, PR-only scheduling of explanatory documentation changes.""" + +import json +import os +from pathlib import Path +import re +import subprocess + + +# Exact paths, not docs/** or *.md: packaged READMEs, generated capability +# reports, schemas, test data, and new/unknown documents still need full CI. +DOCUMENTATION = frozenset( + """ +README.md +docs/architecture/classic-com-contract-evidence-registry.md +docs/architecture/classic-com-generated-unsafe.md +docs/architecture/classic-com-raw-unsafe.md +docs/architecture/classic-com-support.md +docs/architecture/flat-win32-contracts.md +docs/architecture/javascript-binding-internals.md +docs/architecture/winrt-interface-implementations.md +docs/guides/development/ci.md +docs/guides/node/dev-mode.md +docs/guides/python/python-ui-ecosystem.md +docs/guides/windows/classic-com-usage.md +docs/guides/windows/msix-packaging.md +docs/guides/windows/winrt-interface-implementations.md +samples/js/README.md +samples/js/electron-aion-chat/README.md +samples/js/electron-share-ui/README.md +samples/js/electron-smtc/README.md +samples/js/interface-implementation/README.md +samples/js/low-level/README.md +samples/js/ocr/README.md +samples/js/win32/README.md +samples/js/windows-hello/README.md +samples/js/winui-tic-tac-toe-code-only/README.md +samples/js/winui-tic-tac-toe/README.md +samples/python/README.md +samples/python/app-lifecycle-single-instance/README.md +samples/python/app-notification/README.md +samples/python/async-file-io/README.md +samples/python/cryptography/README.md +samples/python/custom-winmd-codegen/README.md +samples/python/device-watcher/README.md +samples/python/interface-implementation/README.md +samples/python/ocr-image/README.md +samples/python/text-to-speech/README.md +samples/python/winui-hello-world/README.md +samples/python/winui-tic-tac-toe-code-only/README.md +samples/python/winui-tic-tac-toe/README.md +""".split() +) + + +def documentation_diff(diff: bytes) -> bool: + if not diff: + return False + fields = diff.decode("utf-8").split("\0") + if fields.pop() != "": + raise ValueError("Git name-status output was not NUL-terminated") + index = 0 + while index < len(fields): + status = fields[index] + count = 2 if re.fullmatch(r"R\d+", status) else 1 + paths = fields[index + 1 : index + 1 + count] + if len(paths) != count: + raise ValueError("Incomplete Git name-status record") + if status not in {"A", "M", "D"} and count != 2: + return False + if any(path not in DOCUMENTATION for path in paths): + return False + index += 1 + count + return True + + +def classify(event_name: str, event: dict, repo: Path) -> bool: + if event_name != "pull_request": + return False + pull_request = event["pull_request"] + base, head = (pull_request[side]["sha"] for side in ("base", "head")) + for sha in (base, head): + if not isinstance(sha, str) or not re.fullmatch(r"[0-9a-f]{40}", sha): + raise ValueError("PR base/head must be full Git commit IDs") + merge_base = subprocess.check_output( + ["git", "merge-base", base, head], cwd=repo + ).decode("ascii").strip() + if not re.fullmatch(r"[0-9a-f]{40}", merge_base): + raise ValueError("Git did not resolve a unique PR merge base") + diff = subprocess.check_output( + ["git", "diff", "--name-status", "--find-renames", "-z", merge_base, head, "--"], + cwd=repo, + ) + return documentation_diff(diff) + + +def main() -> None: + event_name = os.environ["GITHUB_EVENT_NAME"] + event = json.loads(Path(os.environ["GITHUB_EVENT_PATH"]).read_text(encoding="utf-8")) + docs_only = classify(event_name, event, Path.cwd()) + print(f"CI mode: {'documentation-only PR' if docs_only else 'full validation'}") + with open(os.environ["GITHUB_OUTPUT"], "a", encoding="utf-8") as output: + output.write(f"docs_only={str(docs_only).lower()}\n") + + +if __name__ == "__main__": + main() diff --git a/eng/ci/merge-runtime-artifacts.ps1 b/eng/ci/merge-runtime-artifacts.ps1 new file mode 100644 index 00000000..78c61dca --- /dev/null +++ b/eng/ci/merge-runtime-artifacts.ps1 @@ -0,0 +1,26 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +param( + [Parameter(Mandatory)][string]$X64, + [Parameter(Mandatory)][string]$Arm64, + [Parameter(Mandatory)][string]$Output +) + +$ErrorActionPreference = "Stop" +& (Join-Path $PSScriptRoot "artifact.ps1") -Mode Verify -Path $X64 -Kind js -Architecture x64 +& (Join-Path $PSScriptRoot "artifact.ps1") -Mode Verify -Path $Arm64 -Kind js -Architecture arm64 +$left = (Get-Content -LiteralPath (Join-Path $X64 "manifest.json") -Raw | ConvertFrom-Json -AsHashtable).files +$right = (Get-Content -LiteralPath (Join-Path $Arm64 "manifest.json") -Raw | ConvertFrom-Json -AsHashtable).files +$sidecars = @($left.Keys | Where-Object { $_ -notlike "*.node" } | Sort-Object) +$otherSidecars = @($right.Keys | Where-Object { $_ -notlike "*.node" } | Sort-Object) +if (@(Compare-Object $sidecars $otherSidecars).Count) { + throw "Runtime architecture artifacts have different sidecar file sets." +} +foreach ($file in $sidecars) { + if ($left[$file] -cne $right[$file]) { throw "Runtime sidecar differs between architectures: $file" } +} +if (Test-Path -LiteralPath $Output) { throw "Runtime assembly output must not already exist: $Output" } +New-Item -ItemType Directory -Path $Output -Force | Out-Null +Copy-Item -Path (Join-Path $X64 "payload\*") -Destination $Output -Recurse +Copy-Item -LiteralPath (Join-Path $Arm64 "payload\dynwinrt.win32-arm64-msvc.node") -Destination $Output diff --git a/eng/ci/requirements.txt b/eng/ci/requirements.txt new file mode 100644 index 00000000..f62ce0c5 --- /dev/null +++ b/eng/ci/requirements.txt @@ -0,0 +1 @@ +PyYAML==6.0.3 diff --git a/eng/ci/test_ci.py b/eng/ci/test_ci.py new file mode 100644 index 00000000..d3fca010 --- /dev/null +++ b/eng/ci/test_ci.py @@ -0,0 +1,329 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +import copy +import json +import os +from pathlib import Path +import shutil +import struct +import subprocess +import tempfile +import unittest + +import yaml + +from classify_changes import DOCUMENTATION, classify, documentation_diff + + +ROOT = Path(__file__).resolve().parents[2] +CI = ROOT / "eng" / "ci" +WORKFLOW = yaml.safe_load((ROOT / ".github" / "workflows" / "build.yml").read_text(encoding="utf-8")) +JOBS = WORKFLOW["jobs"] +HEAVY = { + "test-rust", "build-codegen-x64", "build-bindings-x64", "build-js-test-hooks", + "build-arm64", "e2e-runtime", "e2e-native", +} +GATES = {"test", "e2e", "dynwinrt", "dynwinrt-codegen", "ci-success"} + + +def powershell(script, *arguments, env=None): + return subprocess.run( + ["pwsh", "-NoProfile", "-File", str(script), *map(str, arguments)], + cwd=ROOT, env=env, text=True, encoding="utf-8", capture_output=True, + ) + + +class ClassificationTests(unittest.TestCase): + def test_conservative_document_allowlist(self): + for path in DOCUMENTATION: + with self.subTest(path=path): + self.assertTrue(documentation_diff(f"M\0{path}\0".encode())) + for path in ( + "docs/status/generated/classic-com-capability-summary.json", + "docs/status/generated/classic-com-interface-support.csv", + "docs/status/generated/classic-com-named-types.md", + "docs/status/TODO.md", "docs/unknown.md", + "contracts/schema/contract.schema.json", "tests/e2e/e2e_specs.schema.json", + "eng/ci/classify_changes.py", ".github/workflows/build.yml", + "bindings/js/README.md", "bindings/py/README.md", + "tools/dynwinrt-codegen/npm/README.md", "tools/dynwinrt-codegen/python/README.md", + "samples/js/ocr/main.ts", "samples/js/ocr/package.json", "crates/dynwinrt/src/lib.rs", + ): + with self.subTest(path=path): + self.assertFalse(documentation_diff(f"M\0README.md\0M\0{path}\0".encode())) + + def test_deletions_renames_unknown_status_and_empty_diff(self): + self.assertTrue(documentation_diff(b"D\0README.md\0")) + self.assertTrue(documentation_diff(b"R100\0README.md\0samples/js/README.md\0")) + self.assertFalse(documentation_diff(b"R100\0src/main.rs\0README.md\0")) + self.assertFalse(documentation_diff(b"R100\0README.md\0src/main.rs\0")) + self.assertFalse(documentation_diff(b"D\0src/main.rs\0A\0README.md\0")) + self.assertFalse(documentation_diff(b"T\0README.md\0")) + self.assertFalse(documentation_diff(b"")) + for malformed in (b"M\0README.md", b"R100\0README.md\0", b"M\0"): + with self.subTest(diff=malformed), self.assertRaises(ValueError): + documentation_diff(malformed) + + def test_entire_pr_history_and_missing_history(self): + with tempfile.TemporaryDirectory(prefix="dynwinrt-ci-git-") as directory: + repo = Path(directory) + + def git(*args): + return subprocess.check_output(["git", *args], cwd=repo).decode().strip() + + git("init", "--quiet") + git("config", "user.name", "CI test") + git("config", "user.email", "ci@example.invalid") + (repo / "README.md").write_text("base\n") + (repo / "code.rs").write_text("base\n") + git("add", ".") + git("commit", "--quiet", "-m", "base") + base = git("rev-parse", "HEAD") + (repo / "code.rs").write_text("changed\n") + git("commit", "--quiet", "-am", "code in earlier PR commit") + (repo / "README.md").write_text("docs in latest commit\n") + git("commit", "--quiet", "-am", "docs") + event = {"pull_request": {"base": {"sha": base}, "head": {"sha": git("rev-parse", "HEAD")}}} + self.assertFalse(classify("pull_request", event, repo)) + # The latest commit alone is docs-only, but the full PR above is not. + event["pull_request"]["base"]["sha"] = git("rev-parse", "HEAD~1") + self.assertTrue(classify("pull_request", event, repo)) + self.assertFalse(classify("push", event, repo)) + self.assertFalse(classify("workflow_dispatch", event, repo)) + event["pull_request"]["head"]["sha"] = "f" * 40 + with self.assertRaises(subprocess.CalledProcessError): + classify("pull_request", event, repo) + event["pull_request"]["head"]["sha"] = "--help" + with self.assertRaises(ValueError): + classify("pull_request", event, repo) + + +class WorkflowTests(unittest.TestCase): + def ancestors(self, job): + needs = JOBS[job].get("needs", []) + if isinstance(needs, str): + needs = [needs] + return set(needs).union(*(self.ancestors(parent) for parent in needs)) + + def test_graph_and_parallel_consumers(self): + self.assertEqual(WORKFLOW["permissions"], {"contents": "read"}) + # PyYAML uses YAML 1.1: an unquoted "on" key is represented by True. + triggers = WORKFLOW.get("on", WORKFLOW.get(True)) + self.assertEqual(set(triggers), {"push", "pull_request"}) + self.assertNotIn("paths-ignore", triggers["pull_request"]) + self.assertEqual(JOBS["changes"]["steps"][0]["with"]["fetch-depth"], 0) + for job in HEAVY: + self.assertEqual(JOBS[job]["if"], "needs.changes.outputs.docs_only == 'false'") + for producer in ("build-codegen-x64", "build-bindings-x64", "build-js-test-hooks", "build-arm64"): + self.assertEqual(set(JOBS[producer]["needs"]), {"format", "changes"}) + for consumer in ("e2e-runtime", "e2e-native"): + self.assertTrue(self.ancestors(consumer).isdisjoint({"test", "test-rust", "build-arm64"})) + for final in ("dynwinrt", "dynwinrt-codegen"): + self.assertTrue({"test", "e2e", "build-arm64"} <= self.ancestors(final)) + self.assertEqual(set(JOBS["ci-success"]["needs"]), set(JOBS) - {"ci-success"}) + + def test_current_run_artifacts_and_no_consumer_rebuilds(self): + uploads = {} + for job, config in JOBS.items(): + for step in config["steps"]: + action = step.get("uses", "") + if action.startswith("actions/upload-artifact@"): + name = step["with"]["name"] + self.assertNotIn(name, uploads) + self.assertEqual(step["with"]["if-no-files-found"], "error") + uploads[name] = job + for job, config in JOBS.items(): + for step in config["steps"]: + if step.get("uses", "").startswith("actions/download-artifact@"): + inputs = step["with"] + self.assertEqual(set(inputs), {"name", "path"}) + producer = uploads[inputs["name"]] + self.assertTrue(producer == job or producer in self.ancestors(job)) + self.assertEqual(uploads["dynwinrt"], "dynwinrt") + self.assertEqual(uploads["dynwinrt-codegen"], "dynwinrt-codegen") + for job in ("e2e-runtime", "e2e-native", "dynwinrt", "dynwinrt-codegen"): + commands = "\n".join(step.get("run", "") for step in JOBS[job]["steps"]) + for forbidden in ("cargo build", "cargo run", "napi build", "maturin build", "npm run test:tsfn", + "npm run test:generated-unsafe", "npm run test:native-completion", + "npm run test:borrowed-copy"): + self.assertNotIn(forbidden, commands) + runtime = "\n".join(step.get("run", "") for step in JOBS["e2e-runtime"]["steps"]) + self.assertIn("cargo test -p dynwinrt-codegen --test implementation_naming_test", runtime) + + def test_gate_truth_tables_execute_the_real_gate(self): + # Run the entire matrix in one PowerShell process, not hundreds of shells. + cases = [] + for job in GATES: + config = JOBS[job] + self.assertEqual(config["if"], "${{ always() }}") + gate_index, gate = next( + (index, step) for index, step in enumerate(config["steps"]) + if "assert-success.ps1" in step.get("run", "") + ) + env = gate["env"] + required = env["REQUIRED_JOBS"].split(",") + skipped = env["DOCS_SKIPPABLE_JOBS"].split(",") + self.assertEqual(set(required), set(config["needs"])) + self.assertEqual(set(skipped), HEAVY & set(required)) + self.assertEqual(env["DOCS_ONLY"], "${{ needs.changes.outputs.docs_only }}") + if job in {"dynwinrt", "dynwinrt-codegen"}: + for step in config["steps"][gate_index + 1:]: + self.assertEqual(step["if"], "needs.changes.outputs.docs_only == 'false'") + for docs in (False, True): + needs = {name: {"result": "skipped" if docs and name in skipped else "success"} for name in required} + needs["changes"]["outputs"] = {"docs_only": str(docs).lower()} + case = {"needs": needs, "required": required, "skipped": skipped, "docs": str(docs).lower(), "ok": True} + cases.append(case) + for dependency in required: + for result in ("success", "failure", "cancelled", "skipped", ""): + if result == needs[dependency]["result"]: + continue + broken = copy.deepcopy(case) + broken["needs"][dependency]["result"] = result + broken["ok"] = False + cases.append(broken) + missing = copy.deepcopy(case) + del missing["needs"][required[-1]] + missing["ok"] = False + cases.append(missing) + unknown = copy.deepcopy(case) + unknown["needs"]["unexpected"] = {"result": "success"} + unknown["ok"] = False + cases.append(unknown) + inconsistent = copy.deepcopy(case) + inconsistent["needs"]["changes"]["outputs"]["docs_only"] = str(not docs).lower() + inconsistent["ok"] = False + cases.append(inconsistent) + with tempfile.TemporaryDirectory(prefix="dynwinrt-ci-gates-") as directory: + cases_path = Path(directory) / "cases.json" + cases_path.write_text(json.dumps(cases)) + harness = Path(directory) / "gates.ps1" + harness.write_text( + 'param([string]$Gate, [string]$Cases)\n' + '$ErrorActionPreference = "Stop"\n' + '$index = 0\n' + 'foreach ($case in (Get-Content $Cases -Raw | ConvertFrom-Json)) {\n' + ' $passed = $true\n' + ' try {\n' + ' & $Gate -NeedsJson ($case.needs | ConvertTo-Json -Depth 5 -Compress) ' + '-RequiredJobs $case.required -DocsOnly $case.docs -SkippableJobs $case.skipped | Out-Null\n' + ' } catch { $passed = $false }\n' + ' if ($passed -ne $case.ok) { throw "Gate truth-table case ${index}: expected $($case.ok)" }\n' + ' $index++\n' + '}\n', + encoding="utf-8", + ) + result = powershell(harness, CI / "assert-success.ps1", cases_path) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + + +class ArtifactTests(unittest.TestCase): + def setUp(self): + self.temporary = tempfile.TemporaryDirectory(prefix="dynwinrt-ci-artifact-") + self.addCleanup(self.temporary.cleanup) + self.root = Path(self.temporary.name) + self.env = {**os.environ, "GITHUB_SHA": "1" * 40, "GITHUB_RUN_ID": "12345"} + + def invoke(self, mode, path, kind="js", arch="x64", *extra, ok=True): + result = powershell( + CI / "artifact.ps1", "-Mode", mode, "-Path", path, "-Kind", kind, + "-Architecture", arch, *extra, env=self.env, + ) + self.assertEqual(result.returncode == 0, ok, result.stdout + result.stderr) + + def payload(self, name, arch="x64", kind="js"): + artifact = self.root / name + payload = artifact / "payload" + payload.mkdir(parents=True) + native = payload / ("dynwinrt-codegen.exe" if kind == "codegen" else f"dynwinrt.win32-{arch}-msvc.node") + image = bytearray(128) + struct.pack_into("&1 | Out-String + if ($LASTEXITCODE -eq 0) { throw "The deliberately failing generation boundary became green: $output" } + $records = @(Get-Content -LiteralPath $trace | ForEach-Object { $_ | ConvertFrom-Json }) + if ($records.Count -ne $Stop) { throw "Expected $Stop invocations, got $($records.Count): $output" } + return $records + } + + $active = (Get-Content (Join-Path $scripts "e2e_specs.json") -Raw | ConvertFrom-Json).specs | + Where-Object { -not $_.skip_reason } + $namespaces = @( + foreach ($lang in @("py", "ts")) { + $active | Where-Object { -not $_.langs -or $lang -in $_.langs } | + Select-Object -ExpandProperty namespace -Unique + } + ) + $winrt = Invoke-GenerationCase "e2e_test.ps1" @{ + SkipBuild = $true; Suite = "standard"; Lang = @("py", "ts"); Python = $shell; Codegen = $prebuilt + } $namespaces.Count + $native = Invoke-GenerationCase "e2e_test.ps1" @{ + SkipBuild = $true; Suite = "standard"; Lang = @("com", "win32"); Python = $shell + } 12 $prebuilt + foreach ($record in @($winrt) + @($native)) { + if ($record.kind -ne "prebuilt" -or $record.arguments[0] -ne "generate") { + throw "Artifact mode invoked Cargo or lost generation arguments" + } + } + if ("Windows.Media" -notin @($native | ForEach-Object { + $index = [Array]::IndexOf($_.arguments, "--namespace") + if ($index -ge 0) { $_.arguments[$index + 1] } + })) { throw "COM interop lost WinRT generation" } + if (($native[-1].arguments -join " ") -notlike "*Windows.Win32.System.Registry.Apis*") { + throw "Flat Win32 generation did not use the prebuilt path" + } + foreach ($language in @("py", "ts")) { + $implementation = Invoke-GenerationCase "implementation_test.ps1" @{ + Lang = @($language); Codegen = $prebuilt + } 1 + if ($implementation.kind -ne "prebuilt") { throw "Implementation generation rebuilt codegen" } + } + $pythonNamespaces = @($active | Where-Object { -not $_.langs -or "py" -in $_.langs } | + Select-Object -ExpandProperty namespace -Unique) + $all = Invoke-GenerationCase "e2e_test.ps1" @{ + SkipBuild = $true; Suite = "all"; Lang = @("py"); Python = $python; Codegen = $prebuilt + } ($pythonNamespaces.Count + 1) + if ($all[-1].kind -ne "prebuilt" -or ($all[-1].arguments -join " ") -notlike "*IBackgroundTask*") { + throw "The full suite did not forward prebuilt codegen into its implementation sub-suite" + } + $fallback = Invoke-GenerationCase "e2e_test.ps1" @{ + SkipBuild = $true; Suite = "standard"; Lang = @("py"); Python = $shell + CargoProfile = "coverage"; CargoTarget = "x86_64-pc-windows-msvc" + } 1 + if ($fallback.kind -ne "cargo" -or ($fallback.arguments -join " ") -notlike + "run -p dynwinrt-codegen --profile coverage --target x86_64-pc-windows-msvc --quiet -- generate *") { + throw "Omitted prebuilt override changed the developer/profile fallback" + } + Write-Host "Prebuilt WinRT/COM/Win32/implementation generation and Cargo fallback regressions passed." +} finally { + if (Test-Path -LiteralPath $scratch) { Remove-Item -LiteralPath $scratch -Recurse -Force } +} +exit 0 From 97c0a2349b4dad1aefec7ba4b9df49fdca9f621e Mon Sep 17 00:00:00 2001 From: Leilei Zhang Date: Fri, 18 Sep 2026 14:54:33 +0800 Subject: [PATCH 6/9] Validate release notes in Build CI Keep checked-in notes and release-task configuration checks in the lightweight gate before parallel producers, including documentation-only runs. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .github/workflows/build.yml | 5 +++++ docs/guides/development/ci.md | 12 +++++++----- eng/ci/test_ci.py | 14 ++++++++++++++ eng/release/README.md | 4 ++++ 4 files changed, 30 insertions(+), 5 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index e1ed3644..c334de18 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -62,6 +62,11 @@ jobs: node --test bindings\js\scripts\run-codegen.test.mjs .\tests\e2e\e2e_preparation.tests.ps1 .\tests\e2e\prebuilt_codegen.tests.ps1 + - name: Validate checked-in release notes + shell: pwsh + run: | + .\eng\release\validate_release_notes.ps1 + .\eng\release\test_validate_release_notes.ps1 # Rust test programs are independent builds, not reusable runtime packages. test-rust: diff --git a/docs/guides/development/ci.md b/docs/guides/development/ci.md index 2ed5bb29..658fb2a6 100644 --- a/docs/guides/development/ci.md +++ b/docs/guides/development/ci.md @@ -56,11 +56,11 @@ allowlisted deletions are documentation changes too. An empty diff uses full validation. Invalid or unavailable history fails classification rather than guessing that the change is documentation-only. -The lightweight path runs the scheduling, artifact and prebuilt-selection -regressions without compiling native code. Stable check names still run and -validate the explicitly expected heavy-job skips; no package artifact is -created. Pushes to `main` and version tags always use full validation. The -workflow is not hidden behind a top-level path filter. +The lightweight path runs the scheduling, artifact, prebuilt-selection and +release-note configuration regressions without compiling native code. Stable +check names still run and validate the explicitly expected heavy-job skips; +no package artifact is created. Pushes to `main` and version tags always use +full validation. The workflow is not hidden behind a top-level path filter. ## Using a prebuilt generator locally @@ -96,6 +96,8 @@ python -m unittest discover -s eng\ci -p "test_*.py" -v node --test bindings\js\scripts\run-codegen.test.mjs .\tests\e2e\e2e_preparation.tests.ps1 .\tests\e2e\prebuilt_codegen.tests.ps1 +.\eng\release\validate_release_notes.ps1 +.\eng\release\test_validate_release_notes.ps1 ``` Parallelism removes the old Rust-test barrier and duplicate release builds; diff --git a/eng/ci/test_ci.py b/eng/ci/test_ci.py index d3fca010..fa65ae1c 100644 --- a/eng/ci/test_ci.py +++ b/eng/ci/test_ci.py @@ -151,6 +151,20 @@ def test_current_run_artifacts_and_no_consumer_rebuilds(self): runtime = "\n".join(step.get("run", "") for step in JOBS["e2e-runtime"]["steps"]) self.assertIn("cargo test -p dynwinrt-codegen --test implementation_naming_test", runtime) + def test_release_notes_validated_in_lightweight_lane(self): + steps = [ + step for step in JOBS["format"]["steps"] + if step.get("name") == "Validate checked-in release notes" + ] + self.assertEqual(len(steps), 1) + self.assertNotIn("if", JOBS["format"]) + self.assertNotIn("if", steps[0]) + self.assertEqual(steps[0]["shell"], "pwsh") + self.assertEqual(steps[0]["run"].splitlines(), [ + r".\eng\release\validate_release_notes.ps1", + r".\eng\release\test_validate_release_notes.ps1", + ]) + def test_gate_truth_tables_execute_the_real_gate(self): # Run the entire matrix in one PowerShell process, not hundreds of shells. cases = [] diff --git a/eng/release/README.md b/eng/release/README.md index 40164904..c92c94f4 100644 --- a/eng/release/README.md +++ b/eng/release/README.md @@ -15,3 +15,7 @@ Do not edit `.pipelines/release.yml` for each release. The Azure DevOps release job explicitly checks out the tagged commit before `GitHubRelease@1` reads the notes, so the contents are snapshotted from the tag commit. Its automatic changelog remains enabled and is appended after the curated notes. + +Build CI and the release pipeline both run `validate_release_notes.ps1` and +`test_validate_release_notes.ps1` to check the notes file, release task inputs, +and source checkout. These checks do not create a tag or publish a release. From c4e3568fb00ea93b348c65583713a25bc4c8ab7d Mon Sep 17 00:00:00 2001 From: Leilei Zhang Date: Fri, 18 Sep 2026 14:59:43 +0800 Subject: [PATCH 7/9] Refresh preview.22 notes through current main Review all 30 merged changes since preview.21, including experimental flat Win32 APIs and cleanup recovery, Python annotations and WinUI teardown, collection strides, COM generation fixes, and OCR setup. Keep precise support and upgrade limits and distinguish Python task progress cleanup from JavaScript event cleanup. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- eng/release/RELEASE_NOTES.md | 106 ++++++++++++++++++++++++----------- 1 file changed, 74 insertions(+), 32 deletions(-) diff --git a/eng/release/RELEASE_NOTES.md b/eng/release/RELEASE_NOTES.md index 8f5c7041..c4f63cd8 100644 --- a/eng/release/RELEASE_NOTES.md +++ b/eng/release/RELEASE_NOTES.md @@ -1,7 +1,8 @@ # dynwinrt 0.1.0-preview.22 -This preview adds standalone WinRT interface implementations, expands safe -Classic COM access, and improves Python usability and Windows examples. +This preview adds standalone WinRT interface implementations and experimental +flat Win32 bindings, expands safe Classic COM access, and improves Python +usability and Windows examples. The npm version is `0.1.0-preview.22`; its Python PEP 440 version is `0.1.0rc22`. ## Highlights @@ -14,6 +15,13 @@ The npm version is `0.1.0-preview.22`; its Python PEP 440 version is `0.1.0rc22` Generated handler declarations cover supported methods, properties, events, structs, arrays, and multiple outputs. See the [interface implementation guide and samples](https://github.com/microsoft/dynwinrt/blob/main/docs/guides/windows/winrt-interface-implementations.md). +- **Experimental flat Win32 bindings for JavaScript/TypeScript.** Generate typed + native-function wrappers from `Windows.Win32.winmd` through the separate + `@microsoft/dynwinrt/win32` entrypoint. Supported contracts provide managed + resources with explicit `close()` and cancellable `readFileAsync()` / + `writeFileAsync()` Promise helpers. New + [Win32 samples](https://github.com/microsoft/dynwinrt/blob/main/samples/js/win32/README.md) + cover system information, Registry queries, and overlapped file I/O. - **Expanded safe Classic COM for JavaScript/TypeScript.** More exact contracts enable `IWbemServices` conditional outputs and owned thumbnail handles. `DynComAudioFormat` validates packed, variable-length `WAVEFORMATEX` headers @@ -23,46 +31,75 @@ The npm version is `0.1.0-preview.22`; its Python PEP 440 version is `0.1.0rc22` `TYMED_HGLOBAL` transfers. - **Typed COM acquisition and bounded copies.** `projectAs(...)`, restricted in-process `IMMDevice.activate(InterfaceClass)`, and Promise-based - `activateAudioInterfaceAsync(...)` simplify managed interface acquisition. + `activateAudioInterfaceAsync(...)` for `IAudioClient`/`IAudioEndpointVolume` + simplify managed interface acquisition. Owned-copy APIs cover audio render/capture, STA-only BGRA8 WIC reads, and linear Media Foundation buffers without exposing borrowed native memory. Audio/MF copy facades are not complete interface projections. Generated unsafe companions and raw ABI access remain explicit escape hatches, not general safe COM support. See the [Classic COM usage guide](https://github.com/microsoft/dynwinrt/blob/main/docs/guides/windows/classic-com-usage.md). -- **Python asyncio task integration.** Generated operations work with +- **Python asyncio and value conversion.** Generated operations work with `asyncio.create_task()` and `TaskGroup.create_task()`, while retaining direct `await`, progress, cancellation, and explicit blocking through `wait()`. -- **Copied bytes and explicit unboxing.** `IBuffer` projections provide safe - copied byte conversion, and `unboxObject()`/`unbox_object()` explicitly convert - supported boxed `IPropertyValue` results without changing generic object - projection. -- **WinUI examples and repeatable setup.** New - [JavaScript](https://github.com/microsoft/dynwinrt/blob/main/samples/js/winui-tic-tac-toe-code-only/README.md) - samples and refreshed - [Python examples](https://github.com/microsoft/dynwinrt/blob/main/samples/python/winui-hello-world/README.md) - demonstrate Windows App SDK initialization and restoring pinned SDK inputs - with WinApp CLI. + In both languages, `IBuffer` projections support copied byte conversion, and + `unboxObject()`/`unbox_object()` explicitly convert supported boxed + `IPropertyValue` results without changing generic object projection. +- **Windows examples and repeatable setup.** + [JavaScript WinUI](https://github.com/microsoft/dynwinrt/blob/main/samples/js/winui-tic-tac-toe-code-only/README.md) + and [Python WinUI](https://github.com/microsoft/dynwinrt/blob/main/samples/python/winui-hello-world/README.md) + examples demonstrate Windows App SDK initialization and pinned WinApp CLI + setup. The repaired + [Windows AI OCR sample](https://github.com/microsoft/dynwinrt/blob/main/samples/js/ocr/README.md) + uses an identity-aware launcher and opt-in model preparation; it requires + supported Windows 11/NPU hardware, Windows App SDK 1.8, and Node.js 24+. - **Local AI chat in Electron.** The [Aion Instruct sample](https://github.com/microsoft/dynwinrt/blob/main/samples/js/electron-aion-chat/README.md) demonstrates streaming responses, cancellation, and multi-turn conversations through generated WinRT bindings. It requires Windows 11 on an ARM64 Snapdragon Copilot+ PC, the Aion preview framework, and its QNN provider. +Repository samples have additional SDK and source-build requirements; follow +their linked setup guides rather than the packaged-runtime minimums below. + WinRT implementation callbacks are synchronous, non-agile, and owner-thread-only; -arbitrary generic implementation roots remain unsupported. The `IBackgroundTask` -samples demonstrate controlled native calls, not OS background activation. -These factories do not provide task registration/triggers, CLSID activation, -package deployment, or COM local-server hosting. +Python implementations require the main interpreter. Arbitrary generic +implementation roots remain unsupported. The `IBackgroundTask` samples +demonstrate controlled native calls, not OS background activation. These +factories do not provide task registration/triggers, CLSID activation, package +deployment, or COM local-server hosting. + +Flat Win32 is a reviewed subset, not a complete Windows API projection; +arbitrary managed native callbacks and variadic functions remain unsupported. +See the [Win32 contract boundaries](https://github.com/microsoft/dynwinrt/blob/main/docs/architecture/flat-win32-contracts.md). ## Improvements and fixes -Python projected-lifetime scopes now enforce thread affinity: same-thread -asyncio tasks can share a scope, while worker threads must create their own -and native callbacks do not inherit a foreign scope. Async progress handlers -are deactivated on completion, cancellation, or release. Generated JavaScript -WinRT subscriptions release temporary delegate references; retaining an -unsubscribe function no longer keeps a removed handler alive. +- **Lifetime cleanup:** Python projected-lifetime scopes enforce thread + affinity: same-thread asyncio tasks can share a scope, but worker threads + need their own and native callbacks do not inherit a foreign scope. Python + asyncio task wrappers clear progress callbacks on completion, cancellation, + and release. + JavaScript subscriptions release temporary delegates, and retained + unsubscribe functions no longer keep removed handlers alive. +- **Collection correctness:** WinRT collection `GetMany` and `ReplaceAll` + operations use native element sizes rather than pointer-sized strides for + small value types, while preserving string and interface ownership. +- **Generated bindings:** Python `.py` and `.pyi` annotations consistently + resolve same-named types, structs, handlers, and delegates. Unsafe COM + companions correctly escape JavaScript binding identifiers and use the + runtime's x86 aggregate descriptor key, fixing affected module imports. +- **UI lifecycle:** Python WinUI activation retains its implementation modules + until process exit to prevent premature unloading during COM teardown. + Object, event, and apartment cleanup remain required; in-process WinUI + unloading is unsupported. The system DispatcherQueue helper loads + CoreMessaging only when a new current-thread queue is needed. +- **Recoverable Win32 cleanup failures:** Failed result cleanup retains owned + resources in `DynWin32CallError.cleanupFailures`; `retryCleanup()` retries + their cleanup without repeating the native call. + +Contributor CI now runs independent builds and Rust checks in parallel, reuses +verified build artifacts for E2E, and retains required validation gates. ## Action required @@ -74,12 +111,16 @@ unsubscribe function no longer keeps a removed handler alive. Runtime and generated package roots remain WinRT-only, with lower-level runtime access isolated under `@microsoft/dynwinrt/com/unsafe` and `@microsoft/dynwinrt/com/unsafe/raw`. -- Ambiguous COM overloads now use explicit - `AtSlot` names; use the generated declarations - instead of an ambiguous unsuffixed call. -- Python `Char16[]` results now match `list[str]`. Regeneration can change - affected long module paths and ambiguous helper/root imports; use generated - namespace exports rather than constructing names. +- Flat Win32 is experimental with no backward-compatibility guarantee yet. + Keep its generated `win32/` modules separate from WinRT and COM, regenerate + with the matching runtime/codegen pair, and validate the APIs you use. +- Previously rejected ambiguous COM overload groups now use explicit + `AtSlot` names. Existing distinguishable + overloads retain their names and dispatch; follow the generated declarations. +- Regenerated Python bindings return `Char16[]` as `list[str]`, matching their + declarations. Regeneration can change affected long module paths and + ambiguous helper/root imports; use generated namespace exports rather than + constructing names. - The first typed incremental Python generation over an older package may need its original WinMD/`--ref` inputs. Supply them or fully regenerate; missing metadata fails without replacing the previous output. See the @@ -97,8 +138,9 @@ python -m pip install --pre "dynwinrt==0.1.0rc22" "dynwinrt-codegen==0.1.0rc22" - `@microsoft/dynwinrt`: JavaScript/TypeScript runtime with Windows x64 and ARM64 native addons for Node.js 18 or later. -- `@microsoft/dynwinrt-codegen`: typed WinRT and supported Classic COM - generation for JavaScript/TypeScript, emitting `.js` and `.d.ts` files. +- `@microsoft/dynwinrt-codegen`: typed WinRT, supported Classic COM, and + experimental flat Win32 generation for JavaScript/TypeScript, emitting + `.js` and `.d.ts` files. - `dynwinrt`: CPython 3.11-3.14 runtime wheels for Windows x64 and ARM64. - `dynwinrt-codegen`: standalone Windows x64 and ARM64 wheels that include a prebuilt generator and require no Rust installation. From d19a685f7752deb5566490e9ad409d05cdfe60c2 Mon Sep 17 00:00:00 2001 From: Leilei Zhang Date: Fri, 18 Sep 2026 15:51:10 +0800 Subject: [PATCH 8/9] Use lightweight CI for Markdown-only pull requests Classify all .md paths case-insensitively without a per-file allowlist, retaining full-PR and rename safeguards. Run package source and README metadata checks in the lightweight lane, with GitHub PowerShell wrapper regressions proving validation failures propagate. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .github/workflows/build.yml | 5 + docs/guides/development/ci.md | 43 +++++--- eng/ci/classify_changes.py | 55 +--------- eng/ci/requirements.txt | 1 + eng/ci/test_ci.py | 112 ++++++++++++++++++-- eng/release/python/verify_python_release.py | 10 ++ 6 files changed, 154 insertions(+), 72 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index c334de18..21c0f5be 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -67,6 +67,11 @@ jobs: run: | .\eng\release\validate_release_notes.ps1 .\eng\release\test_validate_release_notes.ps1 + - name: Validate Python package source metadata + shell: pwsh + run: | + $PSNativeCommandUseErrorActionPreference = $true + python eng\release\python\verify_python_release.py source # Rust test programs are independent builds, not reusable runtime packages. test-rust: diff --git a/docs/guides/development/ci.md b/docs/guides/development/ci.md index 658fb2a6..7c727982 100644 --- a/docs/guides/development/ci.md +++ b/docs/guides/development/ci.md @@ -44,23 +44,41 @@ packaging configurations are not shared with production. ## Documentation-only pull requests -Only pull requests proven to change explanatory documents in the exact allowlist -in `eng/ci/classify_changes.py` take the lightweight path. The list includes the -root README, reviewed usage/architecture guides, and existing sample READMEs. -It does not include packaged READMEs, `docs/status`, generated reports, schemas, -tests, scripts, workflows, sample code/configuration, or unknown paths. +Pull requests that change only `.md` files take the lightweight path. The suffix +match is case-insensitive (`.MD` and `.mD` qualify), but does not include +`.markdown`, `.mdx`, or other file types. New Markdown files in any directory +qualify without editing a path list, including guides, sample and packaged +READMEs, release notes, and `docs/status` Markdown reports. + +There are currently no Markdown exclusions: the repository's Markdown is not +used as generator or native-test behavior input. Package READMEs and release +notes affect published descriptions, not native APIs, so they receive source +metadata and release-note checks rather than native rebuilds. A future +behavior-input exception must identify its exact file and actual consumer; +ordinary documentation must not acquire a directory-wide exclusion. Classification compares the PR merge base to its head using complete Git history, not just the latest commit. Both old and new rename paths must qualify; -allowlisted deletions are documentation changes too. An empty diff uses full -validation. Invalid or unavailable history fails classification rather than -guessing that the change is documentation-only. +renaming code to Markdown or Markdown to code requires full validation. +Markdown additions, modifications and deletions qualify. Any non-Markdown +change, including JSON/CSV baselines, schemas, scripts, workflow files, sample +code/configuration, and unknown non-Markdown paths, requires full validation. +An empty diff uses full validation. Invalid statuses never select the +lightweight path; malformed or unavailable history fails classification +rather than guessing that the change is documentation-only. The lightweight path runs the scheduling, artifact, prebuilt-selection and -release-note configuration regressions without compiling native code. Stable -check names still run and validate the explicitly expected heavy-job skips; -no package artifact is created. Pushes to `main` and version tags always use -full validation. The workflow is not hidden behind a top-level path filter. +release-note configuration regressions, plus Python package source metadata +validation, without compiling native code. The metadata check validates README +declarations, presence and the same description headings checked in wheels; +it does not build wheels. Stable check names still run and validate the +explicitly expected heavy-job skips; no package artifact is created. Pushes +to `main` and version tags always use full validation. The workflow is not +hidden behind a top-level path filter. + +This policy selects jobs in `Build` only. The independent Coverage and Python +release workflows retain their own path filters and can still run for matching +Markdown paths. ## Using a prebuilt generator locally @@ -98,6 +116,7 @@ node --test bindings\js\scripts\run-codegen.test.mjs .\tests\e2e\prebuilt_codegen.tests.ps1 .\eng\release\validate_release_notes.ps1 .\eng\release\test_validate_release_notes.ps1 +python eng\release\python\verify_python_release.py source ``` Parallelism removes the old Rust-test barrier and duplicate release builds; diff --git a/eng/ci/classify_changes.py b/eng/ci/classify_changes.py index ef58e930..e2cf7ffd 100644 --- a/eng/ci/classify_changes.py +++ b/eng/ci/classify_changes.py @@ -1,7 +1,7 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. -"""Conservative, PR-only scheduling of explanatory documentation changes.""" +"""PR-only lightweight scheduling for Markdown changes.""" import json import os @@ -10,52 +10,6 @@ import subprocess -# Exact paths, not docs/** or *.md: packaged READMEs, generated capability -# reports, schemas, test data, and new/unknown documents still need full CI. -DOCUMENTATION = frozenset( - """ -README.md -docs/architecture/classic-com-contract-evidence-registry.md -docs/architecture/classic-com-generated-unsafe.md -docs/architecture/classic-com-raw-unsafe.md -docs/architecture/classic-com-support.md -docs/architecture/flat-win32-contracts.md -docs/architecture/javascript-binding-internals.md -docs/architecture/winrt-interface-implementations.md -docs/guides/development/ci.md -docs/guides/node/dev-mode.md -docs/guides/python/python-ui-ecosystem.md -docs/guides/windows/classic-com-usage.md -docs/guides/windows/msix-packaging.md -docs/guides/windows/winrt-interface-implementations.md -samples/js/README.md -samples/js/electron-aion-chat/README.md -samples/js/electron-share-ui/README.md -samples/js/electron-smtc/README.md -samples/js/interface-implementation/README.md -samples/js/low-level/README.md -samples/js/ocr/README.md -samples/js/win32/README.md -samples/js/windows-hello/README.md -samples/js/winui-tic-tac-toe-code-only/README.md -samples/js/winui-tic-tac-toe/README.md -samples/python/README.md -samples/python/app-lifecycle-single-instance/README.md -samples/python/app-notification/README.md -samples/python/async-file-io/README.md -samples/python/cryptography/README.md -samples/python/custom-winmd-codegen/README.md -samples/python/device-watcher/README.md -samples/python/interface-implementation/README.md -samples/python/ocr-image/README.md -samples/python/text-to-speech/README.md -samples/python/winui-hello-world/README.md -samples/python/winui-tic-tac-toe-code-only/README.md -samples/python/winui-tic-tac-toe/README.md -""".split() -) - - def documentation_diff(diff: bytes) -> bool: if not diff: return False @@ -65,13 +19,14 @@ def documentation_diff(diff: bytes) -> bool: index = 0 while index < len(fields): status = fields[index] - count = 2 if re.fullmatch(r"R\d+", status) else 1 + rename = re.fullmatch(r"R[0-9]{1,3}", status) is not None and int(status[1:]) <= 100 + count = 2 if rename else 1 paths = fields[index + 1 : index + 1 + count] if len(paths) != count: raise ValueError("Incomplete Git name-status record") - if status not in {"A", "M", "D"} and count != 2: + if status not in {"A", "M", "D"} and not rename: return False - if any(path not in DOCUMENTATION for path in paths): + if any(not path.lower().endswith(".md") for path in paths): return False index += 1 + count return True diff --git a/eng/ci/requirements.txt b/eng/ci/requirements.txt index f62ce0c5..4105ab7d 100644 --- a/eng/ci/requirements.txt +++ b/eng/ci/requirements.txt @@ -1 +1,2 @@ PyYAML==6.0.3 +packaging>=24,<27 diff --git a/eng/ci/test_ci.py b/eng/ci/test_ci.py index fa65ae1c..eba5666f 100644 --- a/eng/ci/test_ci.py +++ b/eng/ci/test_ci.py @@ -13,7 +13,7 @@ import yaml -from classify_changes import DOCUMENTATION, classify, documentation_diff +from classify_changes import classify, documentation_diff ROOT = Path(__file__).resolve().parents[2] @@ -35,31 +35,44 @@ def powershell(script, *arguments, env=None): class ClassificationTests(unittest.TestCase): - def test_conservative_document_allowlist(self): - for path in DOCUMENTATION: - with self.subTest(path=path): - self.assertTrue(documentation_diff(f"M\0{path}\0".encode())) + def test_markdown_paths_default_to_lightweight(self): + for path in ( + "README.md", "new/directory/new.md", "docs/guides/new-guide.md", + "samples/new/README.md", "bindings/js/README.md", "bindings/py/README.md", + "tools/dynwinrt-codegen/npm/README.md", "tools/dynwinrt-codegen/python/README.md", + "eng/release/RELEASE_NOTES.md", "docs/status/TODO.md", + "docs/status/generated/classic-com-named-types.md", "docs/status/future-report.md", + "docs/UPPER.MD", "docs/Mixed.mD", "docs/with spaces.md", "docs/with\nnewline.md", + ): + for status in ("A", "M", "D"): + with self.subTest(path=path, status=status): + self.assertTrue(documentation_diff(f"{status}\0{path}\0".encode())) + self.assertTrue(documentation_diff(b"M\0README.md\0A\0future/new.md\0")) + + def test_non_markdown_and_mixed_changes_need_full_validation(self): for path in ( "docs/status/generated/classic-com-capability-summary.json", "docs/status/generated/classic-com-interface-support.csv", - "docs/status/generated/classic-com-named-types.md", - "docs/status/TODO.md", "docs/unknown.md", "contracts/schema/contract.schema.json", "tests/e2e/e2e_specs.schema.json", "eng/ci/classify_changes.py", ".github/workflows/build.yml", - "bindings/js/README.md", "bindings/py/README.md", - "tools/dynwinrt-codegen/npm/README.md", "tools/dynwinrt-codegen/python/README.md", "samples/js/ocr/main.ts", "samples/js/ocr/package.json", "crates/dynwinrt/src/lib.rs", + "future/unknown.data", "docs/guide.markdown", "docs/guide.mdx", "README.md.bak", + "notesmd", "", ): with self.subTest(path=path): + self.assertFalse(documentation_diff(f"A\0{path}\0".encode())) self.assertFalse(documentation_diff(f"M\0README.md\0M\0{path}\0".encode())) def test_deletions_renames_unknown_status_and_empty_diff(self): self.assertTrue(documentation_diff(b"D\0README.md\0")) self.assertTrue(documentation_diff(b"R100\0README.md\0samples/js/README.md\0")) + self.assertTrue(documentation_diff(b"R075\0old/guide.MD\0new/guide.md\0")) self.assertFalse(documentation_diff(b"R100\0src/main.rs\0README.md\0")) self.assertFalse(documentation_diff(b"R100\0README.md\0src/main.rs\0")) self.assertFalse(documentation_diff(b"D\0src/main.rs\0A\0README.md\0")) - self.assertFalse(documentation_diff(b"T\0README.md\0")) + for status in ("T", "U", "X", "C100", "R", "R101", "R1000", "R-1"): + with self.subTest(status=status): + self.assertFalse(documentation_diff(f"{status}\0README.md\0new.md\0".encode())) self.assertFalse(documentation_diff(b"")) for malformed in (b"M\0README.md", b"R100\0README.md\0", b"M\0"): with self.subTest(diff=malformed), self.assertRaises(ValueError): @@ -89,6 +102,14 @@ def git(*args): # The latest commit alone is docs-only, but the full PR above is not. event["pull_request"]["base"]["sha"] = git("rev-parse", "HEAD~1") self.assertTrue(classify("pull_request", event, repo)) + (repo / "new").mkdir() + (repo / "new" / "guide.MD").write_text("new Markdown\n") + git("add", ".") + git("commit", "--quiet", "-m", "new Markdown directory") + event["pull_request"]["head"]["sha"] = git("rev-parse", "HEAD") + self.assertTrue(classify("pull_request", event, repo)) + event["pull_request"]["base"]["sha"] = base + self.assertFalse(classify("pull_request", event, repo)) self.assertFalse(classify("push", event, repo)) self.assertFalse(classify("workflow_dispatch", event, repo)) event["pull_request"]["head"]["sha"] = "f" * 40 @@ -99,6 +120,77 @@ def git(*args): classify("pull_request", event, repo) +class PackageSourceTests(unittest.TestCase): + def setUp(self): + self.temporary = tempfile.TemporaryDirectory(prefix="dynwinrt-ci-source-") + self.addCleanup(self.temporary.cleanup) + self.repo = Path(self.temporary.name) + for relative in ( + "bindings/py/Cargo.toml", "bindings/py/pyproject.toml", "bindings/py/README.md", + "tools/dynwinrt-codegen/Cargo.toml", "tools/dynwinrt-codegen/pyproject.toml", + "tools/dynwinrt-codegen/python/README.md", + "tools/dynwinrt-codegen/src/codegen/package.rs", + "eng/release/python/verify_python_release.py", + ): + target = self.repo / relative + target.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(ROOT / relative, target) + steps = [ + step for step in JOBS["format"]["steps"] + if step.get("name") == "Validate Python package source metadata" + ] + self.assertEqual(len(steps), 1) + self.assertNotIn("if", JOBS["format"]) + self.assertNotIn("if", steps[0]) + self.assertEqual(steps[0]["shell"], "pwsh") + script = self.repo / "step.ps1" + script.write_text( + "$ErrorActionPreference = 'Stop'\n" + + steps[0]["run"] + + "\nif (Test-Path -LiteralPath variable:\\LASTEXITCODE) { exit $LASTEXITCODE }\n", + encoding="utf-8", + ) + quoted_script = str(script).replace("'", "''") + self.command = f". '{quoted_script}'" + + def run_step(self): + return subprocess.run( + ["pwsh", "-NoLogo", "-NoProfile", "-NonInteractive", "-Command", self.command], + cwd=self.repo, text=True, encoding="utf-8", capture_output=True, + ) + + def test_source_step_succeeds_in_github_wrapper(self): + result = self.run_step() + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertIn("source metadata OK:", result.stdout) + + def test_metadata_failure_reaches_github_wrapper(self): + manifest = self.repo / "bindings" / "py" / "Cargo.toml" + original = manifest.read_text(encoding="utf-8") + version = next(line for line in original.splitlines() if line.startswith("version = ")) + manifest.write_text(original.replace(version, 'version = "999.0.0"', 1), encoding="utf-8") + result = self.run_step() + self.assertNotEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertIn("Runtime and codegen Cargo versions must match", result.stdout + result.stderr) + + def test_missing_empty_and_invalid_readmes_fail_in_github_wrapper(self): + for relative in ("bindings/py/README.md", "tools/dynwinrt-codegen/python/README.md"): + readme = self.repo / relative + original = readme.read_bytes() + for contents in (None, "", "# Unrelated package\n"): + with self.subTest(readme=relative, contents=contents): + try: + if contents is None: + readme.unlink() + else: + readme.write_text(contents, encoding="utf-8") + result = self.run_step() + self.assertNotEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertIn("Package README", result.stdout + result.stderr) + finally: + readme.write_bytes(original) + + class WorkflowTests(unittest.TestCase): def ancestors(self, job): needs = JOBS[job].get("needs", []) diff --git a/eng/release/python/verify_python_release.py b/eng/release/python/verify_python_release.py index df033aae..734d6a3f 100644 --- a/eng/release/python/verify_python_release.py +++ b/eng/release/python/verify_python_release.py @@ -70,6 +70,16 @@ def verify_source(tag: str | None, release_version: str | None) -> None: ) assert runtime_project["readme"] == README_SPECS["dynwinrt"] assert codegen_project["readme"] == README_SPECS["dynwinrt-codegen"] + for package, directory in ( + ("dynwinrt", ROOT / "bindings" / "py"), + ("dynwinrt-codegen", ROOT / "tools" / "dynwinrt-codegen"), + ): + readme = directory / README_SPECS[package]["file"] + assert readme.is_file(), f"Package README is missing: {readme}" + expected_heading = README_HEADINGS[package] + assert readme.read_text(encoding="utf-8").strip().startswith(expected_heading), ( + f"Package README {readme} must start with {expected_heading!r}" + ) generated_manifest = ( ROOT / "tools" / "dynwinrt-codegen" / "src" / "codegen" / "package.rs" From 9ab66beed597d363c1adee1caeeb55d9f6e749bb Mon Sep 17 00:00:00 2001 From: Leilei Zhang Date: Fri, 18 Sep 2026 15:54:44 +0800 Subject: [PATCH 9/9] Keep the generic release text in the checked-in notes Restore the original Packages, Installation, and What's Included template with a literal preview.22 heading. Preserve external release-note loading and the detailed notes in existing history, so release content can be refined separately. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- eng/release/README.md | 13 +-- eng/release/RELEASE_NOTES.md | 162 ++++------------------------------- 2 files changed, 25 insertions(+), 150 deletions(-) diff --git a/eng/release/README.md b/eng/release/README.md index c92c94f4..61e3caef 100644 --- a/eng/release/README.md +++ b/eng/release/README.md @@ -1,20 +1,21 @@ # Release notes -`RELEASE_NOTES.md` is the checked-in, curated description for the next public -release. Version-specific installation commands are intentional so each GitHub -Release remains a useful snapshot. +`RELEASE_NOTES.md` is the checked-in description for the next public release. +Generic package and installation text or release-specific highlights belong +in that file, without requiring pipeline changes. Use a literal release +heading: file-based notes do not expand Azure DevOps variables. Before each public release: -1. Update only `RELEASE_NOTES.md` for the release-note content, including every - version and installation command. +1. Update only `RELEASE_NOTES.md` for the release-note content, including the + release heading and any version-specific installation commands. 2. Merge the release preparation to `main`. 3. Tag that exact `main` commit. Do not edit `.pipelines/release.yml` for each release. The Azure DevOps release job explicitly checks out the tagged commit before `GitHubRelease@1` reads the notes, so the contents are snapshotted from the tag commit. Its automatic -changelog remains enabled and is appended after the curated notes. +changelog remains enabled and is appended after the checked-in notes. Build CI and the release pipeline both run `validate_release_notes.ps1` and `test_validate_release_notes.ps1` to check the notes file, release task inputs, diff --git a/eng/release/RELEASE_NOTES.md b/eng/release/RELEASE_NOTES.md index c4f63cd8..f6bf70d2 100644 --- a/eng/release/RELEASE_NOTES.md +++ b/eng/release/RELEASE_NOTES.md @@ -1,151 +1,25 @@ -# dynwinrt 0.1.0-preview.22 +## Prerelease v0.1.0-preview.22 -This preview adds standalone WinRT interface implementations and experimental -flat Win32 bindings, expands safe Classic COM access, and improves Python -usability and Windows examples. -The npm version is `0.1.0-preview.22`; its Python PEP 440 version is `0.1.0rc22`. +**Packages:** +- `@microsoft/dynwinrt` - JavaScript/TypeScript bindings for WinRT dynamic invocation +- `@microsoft/dynwinrt-codegen` - Code generation tool for typed WinRT bindings +- `dynwinrt` - Native Python runtime for generated WinRT projections +- `dynwinrt-codegen` - Standalone Python code generation tool -## Highlights +## Installation -- **Implement WinRT interfaces in Node.js/TypeScript and Python.** - `IBackgroundTask.implement(handlers)` and other supported interface factories - create standalone `IInspectable` objects without a composable WinUI base. - The typed management handle exposes a stable `impl.value` and `impl.dispose()`; - Python also supports `with IBackgroundTask.implement(handler) as impl:`. - Generated handler declarations cover supported methods, properties, events, - structs, arrays, and multiple outputs. See the - [interface implementation guide and samples](https://github.com/microsoft/dynwinrt/blob/main/docs/guides/windows/winrt-interface-implementations.md). -- **Experimental flat Win32 bindings for JavaScript/TypeScript.** Generate typed - native-function wrappers from `Windows.Win32.winmd` through the separate - `@microsoft/dynwinrt/win32` entrypoint. Supported contracts provide managed - resources with explicit `close()` and cancellable `readFileAsync()` / - `writeFileAsync()` Promise helpers. New - [Win32 samples](https://github.com/microsoft/dynwinrt/blob/main/samples/js/win32/README.md) - cover system information, Registry queries, and overlapped file I/O. -- **Expanded safe Classic COM for JavaScript/TypeScript.** More exact contracts - enable `IWbemServices` conditional outputs and owned thumbnail handles. - `DynComAudioFormat` validates packed, variable-length `WAVEFORMATEX` headers - and `cbSize` extensions; safe `IAudioClient`/`IAudioClient2`/`IAudioClient3` - projections manage CoTaskMem-owned format outputs. Dedicated - `FORMATETC`/`STGMEDIUM` support covers target-device-independent - `TYMED_HGLOBAL` transfers. -- **Typed COM acquisition and bounded copies.** `projectAs(...)`, restricted - in-process `IMMDevice.activate(InterfaceClass)`, and Promise-based - `activateAudioInterfaceAsync(...)` for `IAudioClient`/`IAudioEndpointVolume` - simplify managed interface acquisition. - Owned-copy APIs cover audio render/capture, STA-only BGRA8 WIC reads, and - linear Media Foundation buffers without exposing borrowed native memory. - Audio/MF copy facades are not complete interface projections. Generated - unsafe companions and raw ABI access remain explicit escape hatches, not - general safe COM support. - See the [Classic COM usage guide](https://github.com/microsoft/dynwinrt/blob/main/docs/guides/windows/classic-com-usage.md). -- **Python asyncio and value conversion.** Generated operations work with - `asyncio.create_task()` and `TaskGroup.create_task()`, while retaining direct - `await`, progress, cancellation, and explicit blocking through `wait()`. - In both languages, `IBuffer` projections support copied byte conversion, and - `unboxObject()`/`unbox_object()` explicitly convert supported boxed - `IPropertyValue` results without changing generic object projection. -- **Windows examples and repeatable setup.** - [JavaScript WinUI](https://github.com/microsoft/dynwinrt/blob/main/samples/js/winui-tic-tac-toe-code-only/README.md) - and [Python WinUI](https://github.com/microsoft/dynwinrt/blob/main/samples/python/winui-hello-world/README.md) - examples demonstrate Windows App SDK initialization and pinned WinApp CLI - setup. The repaired - [Windows AI OCR sample](https://github.com/microsoft/dynwinrt/blob/main/samples/js/ocr/README.md) - uses an identity-aware launcher and opt-in model preparation; it requires - supported Windows 11/NPU hardware, Windows App SDK 1.8, and Node.js 24+. -- **Local AI chat in Electron.** The - [Aion Instruct sample](https://github.com/microsoft/dynwinrt/blob/main/samples/js/electron-aion-chat/README.md) - demonstrates streaming responses, cancellation, and multi-turn conversations - through generated WinRT bindings. It requires Windows 11 on an ARM64 - Snapdragon Copilot+ PC, the Aion preview framework, and its QNN provider. - -Repository samples have additional SDK and source-build requirements; follow -their linked setup guides rather than the packaged-runtime minimums below. - -WinRT implementation callbacks are synchronous, non-agile, and owner-thread-only; -Python implementations require the main interpreter. Arbitrary generic -implementation roots remain unsupported. The `IBackgroundTask` samples -demonstrate controlled native calls, not OS background activation. These -factories do not provide task registration/triggers, CLSID activation, package -deployment, or COM local-server hosting. - -Flat Win32 is a reviewed subset, not a complete Windows API projection; -arbitrary managed native callbacks and variadic functions remain unsupported. -See the [Win32 contract boundaries](https://github.com/microsoft/dynwinrt/blob/main/docs/architecture/flat-win32-contracts.md). - -## Improvements and fixes - -- **Lifetime cleanup:** Python projected-lifetime scopes enforce thread - affinity: same-thread asyncio tasks can share a scope, but worker threads - need their own and native callbacks do not inherit a foreign scope. Python - asyncio task wrappers clear progress callbacks on completion, cancellation, - and release. - JavaScript subscriptions release temporary delegates, and retained - unsubscribe functions no longer keep removed handlers alive. -- **Collection correctness:** WinRT collection `GetMany` and `ReplaceAll` - operations use native element sizes rather than pointer-sized strides for - small value types, while preserving string and interface ownership. -- **Generated bindings:** Python `.py` and `.pyi` annotations consistently - resolve same-named types, structs, handlers, and delegates. Unsafe COM - companions correctly escape JavaScript binding identifiers and use the - runtime's x86 aggregate descriptor key, fixing affected module imports. -- **UI lifecycle:** Python WinUI activation retains its implementation modules - until process exit to prevent premature unloading during COM teardown. - Object, event, and apartment cleanup remain required; in-process WinUI - unloading is unsupported. The system DispatcherQueue helper loads - CoreMessaging only when a new current-thread queue is needed. -- **Recoverable Win32 cleanup failures:** Failed result cleanup retains owned - resources in `DynWin32CallError.cleanupFailures`; `retryCleanup()` retries - their cleanup without repeating the native call. - -Contributor CI now runs independent builds and Rust checks in parallel, reuses -verified build artifacts for E2E, and retains required validation gates. - -## Action required - -- Use Node.js 18 or later, keep runtime and codegen versions matched, and - regenerate affected bindings. -- Fully regenerate Classic COM bindings; do not mix old and new modules. - Outputs use canonical `com/` and `com/unsafe/` paths, not legacy flat paths. - Import COM through the explicit `@microsoft/dynwinrt/com` entrypoint. - Runtime and generated package roots remain WinRT-only, with lower-level - runtime access isolated under - `@microsoft/dynwinrt/com/unsafe` and `@microsoft/dynwinrt/com/unsafe/raw`. -- Flat Win32 is experimental with no backward-compatibility guarantee yet. - Keep its generated `win32/` modules separate from WinRT and COM, regenerate - with the matching runtime/codegen pair, and validate the APIs you use. -- Previously rejected ambiguous COM overload groups now use explicit - `AtSlot` names. Existing distinguishable - overloads retain their names and dispatch; follow the generated declarations. -- Regenerated Python bindings return `Char16[]` as `list[str]`, matching their - declarations. Regeneration can change affected long module paths and - ambiguous helper/root imports; use generated namespace exports rather than - constructing names. -- The first typed incremental Python generation over an older package may - need its original WinMD/`--ref` inputs. Supply them or fully regenerate; - missing metadata fails without replacing the previous output. See the - [generator upgrade guidance](https://github.com/microsoft/dynwinrt/blob/main/tools/dynwinrt-codegen/README.md). - -## Install - -```powershell -npm install @microsoft/dynwinrt@0.1.0-preview.22 -npm install -D @microsoft/dynwinrt-codegen@0.1.0-preview.22 -python -m pip install --pre "dynwinrt==0.1.0rc22" "dynwinrt-codegen==0.1.0rc22" +```bash +npm install @microsoft/dynwinrt +npm install -D @microsoft/dynwinrt-codegen +python -m pip install --pre dynwinrt dynwinrt-codegen ``` -## Packages/platforms - -- `@microsoft/dynwinrt`: JavaScript/TypeScript runtime with Windows x64 and - ARM64 native addons for Node.js 18 or later. -- `@microsoft/dynwinrt-codegen`: typed WinRT, supported Classic COM, and - experimental flat Win32 generation for JavaScript/TypeScript, emitting - `.js` and `.d.ts` files. -- `dynwinrt`: CPython 3.11-3.14 runtime wheels for Windows x64 and ARM64. -- `dynwinrt-codegen`: standalone Windows x64 and ARM64 wheels that include a - prebuilt generator and require no Rust installation. +## What's Included -Consuming the packaged binaries and generated bindings requires no native -compiler. Python code generation remains WinRT-only. +- ✅ Native addons for x64 and ARM64 +- ✅ TypeScript type definitions +- ✅ dynwinrt-codegen CLI for code generation +- ✅ CPython 3.11–3.14 runtime wheels for Windows x64 and ARM64 +- ✅ Standalone Python codegen wheels for Windows x64 and ARM64 -**Detailed changes:** [v0.1.0-preview.21...v0.1.0-preview.22](https://github.com/microsoft/dynwinrt/compare/v0.1.0-preview.21...v0.1.0-preview.22) +For usage instructions, see the [README](https://github.com/microsoft/dynwinrt#readme).