diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 8a7afdaa..a82840db 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -18,8 +18,14 @@ contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additio - **Rust** (stable, 2024 edition) - **Windows 10/11** with Windows SDK installed +- **Node.js 18+** for the JavaScript binding and generated JavaScript tests +- **CPython 3.11–3.14** plus `maturin` for the Python binding - **libffi** (bundled via the `libffi` crate) +Some suites also require Windows App SDK metadata/runtime assets or +`Microsoft.Windows.SDK.Win32Metadata`; the test scripts skip optional suites +unless those inputs are explicitly required. + ### Building ```bash @@ -28,6 +34,12 @@ cargo build -p dynwinrt # Build the code generator cargo build -p dynwinrt-codegen + +# Build the JavaScript binding +(cd bindings/js && npm install && npm run build) + +# Build/install the Python binding +(cd bindings/py && python -m maturin develop) ``` ### Running Tests @@ -38,6 +50,15 @@ cargo test -p dynwinrt # Code generator tests cargo test -p dynwinrt-codegen + +# JavaScript tests +(cd bindings/js && npm test) + +# Python tests +(cd bindings/py && python -m pytest) + +# End-to-end tests (auto-detects available metadata) +pwsh -File ./tests/e2e/e2e_test.ps1 ``` ### Coverage @@ -76,7 +97,7 @@ Please use the provided issue templates when available. 1. Fork the repo and create your branch from `main` 2. If you've added code, add tests that cover the new functionality -3. Ensure all tests pass (`cargo test`) +3. Ensure the relevant Rust and language-binding tests pass 4. Run `cargo clippy` and address any warnings 5. Submit your pull request diff --git a/README.md b/README.md index 533acbd6..17edd114 100644 --- a/README.md +++ b/README.md @@ -1,35 +1,31 @@ # dynwinrt -**Call any Windows Runtime (WinRT) API from JavaScript or TypeScript — without writing a native addon.** +**Call Windows Runtime (WinRT) APIs from JavaScript, TypeScript, or Python — without writing a native extension.** [![@microsoft/dynwinrt](https://img.shields.io/npm/v/@microsoft/dynwinrt.svg?label=%40microsoft%2Fdynwinrt)](https://www.npmjs.com/package/@microsoft/dynwinrt) [![@microsoft/dynwinrt-codegen](https://img.shields.io/npm/v/@microsoft/dynwinrt-codegen.svg?label=%40microsoft%2Fdynwinrt-codegen)](https://www.npmjs.com/package/@microsoft/dynwinrt-codegen) +[![dynwinrt on PyPI](https://img.shields.io/pypi/v/dynwinrt.svg?label=PyPI%20dynwinrt)](https://pypi.org/project/dynwinrt/) +[![dynwinrt-codegen on PyPI](https://img.shields.io/pypi/v/dynwinrt-codegen.svg?label=PyPI%20dynwinrt-codegen)](https://pypi.org/project/dynwinrt-codegen/) [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE) ## Why dynwinrt? If you've ever tried to call a modern Windows API (WinAppSDK, Windows AI, notifications, file pickers, sensors, …) from an Electron, Node, or Python app, you've probably hit one of these walls: -- **Writing a C++ `node-addon-api` addon** — needs `node-gyp`, MSVC, Python, the matching Windows SDK, and a CI matrix per Electron version. -- **Writing a C# addon via `node-api-dotnet`** — needs the .NET SDK, a `csproj` build step, and a hand-maintained wrapper for every API surface you want to expose. +- **Writing a native extension for each API surface** — needs C++, Rust, or C#, the matching Windows SDK, and language-specific build tooling. +- **Bridging through another runtime** — adds deployment dependencies and a hand-maintained wrapper for every API you expose. - **Waiting for an official projection** — Windows ships `.winmd` metadata months before any JavaScript- or Python-friendly projection appears in a published package. -`dynwinrt` removes all of that. It reads the same `.winmd` metadata your Windows SDK / WinAppSDK NuGet packages already ship and calls the underlying COM vtables **dynamically at runtime via libffi**. The codegen emits typed `.js` + `.d.ts` wrappers; the runtime invokes them through `dynwinrt`'s native binary. No MSBuild step in your app, no `node-gyp`, no per-Windows-version recompile. +`dynwinrt` reads the same `.winmd` metadata shipped by the Windows SDK and WinAppSDK, then calls the underlying COM vtables **dynamically at runtime via libffi**. The codegen emits typed `.js` + `.d.ts` or `.py` + `.pyi` wrappers; the matching native runtime invokes them. Consuming applications do not need MSBuild, `node-gyp`, Cargo, or a native compiler. -```ts -import { LanguageModel } from './bindings/winrt'; - -const model = await LanguageModel.createAsync(); -const result = await model.generateResponseAsync('Tell me a joke'); -console.log(result.text); -``` - -That's the whole story: install, generate, import, call. - -> **Scope** — `dynwinrt` primarily targets **data-style WinRT APIs**. WinUI `Application + Window` hosting is also supported on a caller-managed STA UI thread; the application remains responsible for package identity and lifecycle. +> **Scope** — `dynwinrt` primarily targets **data-style WinRT APIs**. WinUI +> `Application + Window` hosting is also supported on a caller-managed STA UI +> thread. Classic COM has a separate preview surface described below. ## Quick start +### JavaScript / TypeScript + ```bash npm install @microsoft/dynwinrt npm install -D @microsoft/dynwinrt-codegen @@ -50,29 +46,51 @@ const uri = new Uri('https://example.com/path?q=1'); console.log(uri.host); // "example.com" ``` -Classic COM bindings import their runtime API from the separate -`@microsoft/dynwinrt/com/unsafe` subpath internally. Applications use -`@microsoft/dynwinrt/com` for initialization and managed COM value types; -manual ABI declarations require an explicit `/com/unsafe` import. All are -part of the same npm package, while the package root remains WinRT-only. See -[Classic COM support](docs/architecture/classic-com-support.md) for the supported ABI, -common-interface test matrix, unsupported native types, and ownership rules. -See [Classic COM JavaScript usage](docs/guides/windows/classic-com-usage.md) for codegen, -GUID/IID/CLSID, lifecycle, generated same-thread event sinks, Automation, and explicit unsafe ABI -examples. - -Generated bindings project unambiguous public WinRT activation metadata as JavaScript -constructors, including overloads such as `new Uri(base, relative)`. Existing -static factory methods remain available. Classes that can only be returned by -the system, or that expose only protected composition, remain non-constructible; -Python stubs do not advertise their internal native-value wrapping path. -Bindings also include async + progress support, generic collections -(`IVector`, `IMap`), structs, enums, and delegates — see -`tools/dynwinrt-codegen/npm/README.md` for the full feature list. +### Python + +```powershell +python -m pip install --pre dynwinrt dynwinrt-codegen + +# Generate and install one typed projection package. +dynwinrt-codegen generate ` + --namespace Windows.Foundation ` + --class-name Uri ` + --lang py ` + --output .\generated_uri +python -m pip install .\generated_uri +``` + +```python +from dynwinrt import RoApartment, projected_lifetime_scope +from generated_uri.windows.foundation import Uri + +with RoApartment(1), projected_lifetime_scope(): + uri = Uri("https://example.com/path?q=1") + print(uri.host) # "example.com" +``` + +Initialize one apartment per thread that uses WinRT. Use `RoApartment(1)` for a +normal MTA thread and `RoApartment(0)` for an STA UI thread. The projection +lifetime scope releases generated wrappers before the apartment closes. + +## Generated API + +Both projections expose public WinRT activation metadata as normal +constructors, preserve static factory methods, and generate properties, +overloads, async operations with progress, collections, structs, enums, +delegates, and events. JavaScript uses camelCase names; Python uses snake_case +names, native Python values, asyncio-compatible awaitables, and type stubs. + +- [JavaScript/TypeScript codegen package guide](tools/dynwinrt-codegen/npm/README.md) +- [Python codegen package guide](tools/dynwinrt-codegen/python/README.md) +- [Python runtime guide](bindings/py/README.md) ### WinUI `Application + Window` -When `Microsoft.UI.Xaml.Application` is selected, JavaScript codegen also emits `XamlControlsXamlMetaDataProvider` and `XamlControlsResources`. Use the generated helper to compose the application outer, register WinUI metadata, and install the default Fluent resources before creating controls: +When `Microsoft.UI.Xaml.Application` is selected, codegen emits helpers for +WinUI metadata and `XamlControlsResources`. The application remains responsible +for package identity, framework bootstrap, UI-thread ownership, and lifecycle. +For JavaScript: ```js const { initWinappsdk, roInitialize } = require('@microsoft/dynwinrt'); @@ -102,25 +120,66 @@ This keeps WinUI async completions and JavaScript Promise checkpoints working while XAML owns the thread. `Application.start()` remains available when the exact blocking WinRT call is required, but it pauses the Node event loop. +Python uses `Application.start()` inside `RoApartment(0)` and +`projected_lifetime_scope()`. See the +[Python WinUI hello-world sample](samples/python/winui-hello-world/) and +[Python-defined WinUI control sample](samples/python/winui-tic-tac-toe/). + In an unpackaged process, set `WINAPPSDK_BOOTSTRAP_DLL_PATH` to the architecture-matched -`Microsoft.WindowsAppRuntime.Bootstrap.dll` before calling `initWinappsdk()`. +`Microsoft.WindowsAppRuntime.Bootstrap.dll` before calling JavaScript +`initWinappsdk()` or Python `init_winappsdk()`. `Application.create()` resolves the bootstrapped framework resources and configures its UI thread for Per-Monitor V2 DPI awareness. Packaged processes can omit the bootstrap call. +## Classic COM (Preview) + +Classic COM support is functional and tested, but remains a **preview under +active development**. It targets a conservatively validated subset of +`IUnknown`- and `IInspectable`-rooted interfaces from `Windows.Win32.winmd`; it +is not a general Automation or native Win32 projection, and it does not project +flat DLL exports. + +The current CI baseline against +`Microsoft.Windows.SDK.Win32Metadata` 71.0.14-preview is **5,567 of 7,929 +eligible interfaces (70.21%)** with complete safe code generation. Supported +contracts include generated coclass activation and QueryInterface views, +managed interface ownership, native POD layouts, typed counted buffers, +BSTR/HSTRING, validated VARIANT, SAFEARRAY and PROPVARIANT subsets, and +synchronous JavaScript implementations of fully supported callback interfaces. +Seventeen stock-Windows Node E2E runners exercise representative Shell, +Automation, stream, callback, HWND, and WinRT interop scenarios. + +Safety takes priority over coverage. If metadata does not fully describe an +interface's ABI, layout, ownership, allocator, or cleanup contract, generation +fails before emitting a partial wrapper. Material gaps still include several +common graphics, audio, WMI, clipboard/drag-and-drop, derived Automation, union, +BYREF/InOut, and output-ownership shapes. + +Classic COM generation currently emits JavaScript and TypeScript only. It uses +the separate `@microsoft/dynwinrt/com` public surface; generated wrappers call +`@microsoft/dynwinrt/com/unsafe` internally after codegen validates the ABI. +The `@microsoft/dynwinrt` package root remains WinRT-only. + +- [Classic COM JavaScript usage guide](docs/guides/windows/classic-com-usage.md) +- [Supported ABI, coverage, limitations, and ownership model](docs/architecture/classic-com-support.md) + ## Repository layout ``` dynwinrt/ -├── crates/dynwinrt/ # Core Rust runtime (FFI, metadata, async, delegates, collections) +├── .github/ +│ └── workflows/ # CI, coverage, and Python wheel assembly +├── .pipelines/ # Official 1ES npm, PyPI, and GitHub release pipeline +├── crates/dynwinrt/ # Shared WinRT + Classic COM ABI/libffi runtime ├── bindings/ -│ ├── js/ # @microsoft/dynwinrt — JS / TS bindings (napi-rs) -│ └── py/ # Python bindings (PyO3; release workflow ready) +│ ├── js/ # @microsoft/dynwinrt npm runtime (N-API) +│ └── py/ # dynwinrt PyPI runtime (PyO3) ├── tools/ -│ └── dynwinrt-codegen/ # @microsoft/dynwinrt-codegen — typed-binding generator +│ └── dynwinrt-codegen/ # npm + PyPI WinRT/Classic COM codegen CLI ├── tests/ -│ └── e2e/ # Cross-language E2E specs, runners, and scripts +│ └── e2e/ # JavaScript, Python, and Classic COM E2E suites ├── benchmarks/ │ ├── electron/ # Electron IPC benchmark app │ └── js/ # Dynamic and static JS/native benchmarks @@ -128,7 +187,9 @@ dynwinrt/ │ ├── js/ # JavaScript/TypeScript samples │ └── python/ # Python samples ├── docs/ # Architecture, benchmark, guide, and status docs -└── eng/release/python/ # Python release verification helpers +└── eng/ + ├── coverage/ # Mixed Rust/JavaScript/Python coverage tooling + └── release/python/ # Python release preparation and verification ``` ## Build from source @@ -142,17 +203,17 @@ cargo test -p dynwinrt cd bindings/js && npm install && npm run build # Python bindings (PyO3 + maturin) -cd bindings/py && maturin develop && pytest +cd bindings/py && python -m maturin develop && python -m pytest # Codegen tool cargo build -p dynwinrt-codegen --release cargo run -p dynwinrt-codegen -- generate --namespace Windows.Foundation --class-name Uri --output ./generated ``` -Python runtime wheels target CPython 3.11–3.14 on Windows x64 and ARM64. The -standalone `dynwinrt-codegen` Python wheel targets CPython 3.8–3.14 and needs no -Rust installation at consumption time. Release and ESRP publishing -instructions are in [`bindings/py/README.md`](bindings/py/README.md). +Python [`dynwinrt`](https://pypi.org/project/dynwinrt/) runtime wheels target +CPython 3.11–3.14 on Windows x64 and ARM64. The standalone +[`dynwinrt-codegen`](https://pypi.org/project/dynwinrt-codegen/) wheel runs on +Python 3.8–3.14 and needs no Rust installation at consumption time. Python runtime, codegen, packaging, and WinUI readiness are tracked in [`docs/status/PYTHON_CHECKLIST.md`](docs/status/PYTHON_CHECKLIST.md). @@ -179,18 +240,24 @@ For deployment, see | Argument | Required | Description | |---|---|---| | `--winmd PATH[;PATH...]` | No | Path to `.winmd` file(s) (auto-detects Windows SDK if omitted) | +| `--winmd-list FILE` | No | Newline-separated `.winmd` paths to emit | | `--folder PATH` | No | Directory containing `.winmd` files | | `--namespace NAMESPACE` | No | WinRT namespace to generate (omit for all non-`Windows.*` namespaces) | -| `--class-name CLASS` | No | Specific class (transitively pulls in dependencies) | -| `--ref PATH` | No | Additional `.winmd` files for type resolution only (no code emitted) | +| `--class-name NAME[,NAME...]` | No | Specific classes or public interfaces; dependencies are resolved transitively | +| `--ref PATH[;PATH...]` | No | Additional `.winmd` files for type resolution only (no code emitted) | +| `--ref-list FILE` | No | Newline-separated reference metadata paths | | `--lang LANG` | No | `js` (default, emits `.js` + `.d.ts`) or `py` (emits `.py` + `.pyi` and `py.typed`) | +| `--import-name NAME` | No | JavaScript runtime import name (default `@microsoft/dynwinrt`) | +| `--pyi` | No | Explicitly request the default Python type stubs | | `--no-pyi` | No | With `--lang py`, emit implementation files without type stubs | | `--output DIR` | No | Output directory (default `./generated`) | | `--dry-run` | No | Validate input, don't write files | -For each WinRT class the codegen emits a typed wrapper, factory, interface registration, async + progress support, generic collections, structs, enums, delegates, and an `index.js` / `index.d.ts` that re-exports every emitted symbol. +For the complete language-specific behavior and examples, see the +[JavaScript/TypeScript](tools/dynwinrt-codegen/npm/README.md) and +[Python](tools/dynwinrt-codegen/python/README.md) codegen package guides. -## Local development — fix import paths in generated files +## JavaScript local development — fix generated imports Generated files import from `'@microsoft/dynwinrt'`. When iterating against a locally-built runtime, rewrite imports to the relative path: @@ -205,8 +272,8 @@ find generated -name "*.js" -exec sed -i "s|from '@microsoft/dynwinrt'|from '../ | `cargo build` fails with libffi errors | Ensure you have a C compiler (MSVC) and the Windows SDK installed | | `cargo test -p dynwinrt` fails | Windows SDK must be installed at the default path with `Windows.winmd` | | JS bindings won't build | Run `npm install` first; requires Node.js 18+ | -| Python bindings won't build | Requires Python 3.8+ and `maturin` (`pip install maturin`) | -| Codegen snapshot tests fail | Line-ending differences — run `cargo test -p dynwinrt-codegen -- --include-ignored` to regenerate | +| Python bindings won't build | Requires CPython 3.11–3.14 and `maturin` (`python -m pip install maturin`) | +| Codegen snapshot tests fail after an intentional change | Set `DYNWINRT_UPDATE_SNAPSHOTS=1` for JavaScript snapshots or `DYNWINRT_UPDATE_PY_SNAPSHOTS=1` for Python snapshots, then rerun the affected test | ## Contributing diff --git a/bindings/js/README.md b/bindings/js/README.md index 0ad1b018..973fbc6b 100644 --- a/bindings/js/README.md +++ b/bindings/js/README.md @@ -1,6 +1,6 @@ # @microsoft/dynwinrt -**Call any Windows Runtime (WinRT) API from JavaScript — without writing a native addon.** +**Call Windows Runtime (WinRT) APIs from JavaScript — without writing a native addon.** `dynwinrt` is a runtime library that lets your Node.js or Electron code call modern Windows APIs (WinAppSDK, Windows AI, notifications, file pickers, sensors, storage, networking, …) **directly from JavaScript / TypeScript**, with full IntelliSense, no MSBuild step, no C++ or C# project, and no per-Windows-version recompile. @@ -12,7 +12,12 @@ If you've ever tried to call a Windows API from an Electron or Node app, you've - **Writing a C# addon via `node-api-dotnet`.** Needs the .NET SDK, a separate `csproj` build step, and a manually-maintained C# wrapper for every API surface you want to expose. - **Waiting for a typed projection.** Some Windows APIs ship `.winmd` metadata months before any JavaScript-friendly projection appears in a published package. -`dynwinrt` removes all of that. It reads the `.winmd` metadata that ships with the Windows SDK (and WinAppSDK NuGet packages) at **runtime**, resolves the COM vtables, and invokes WinRT methods dynamically. There is no native build step in your Electron project. There is no version pinning — the same generated bindings work across Windows SDK / WinAppSDK revisions as long as the metadata is forward-compatible. You just install `@microsoft/dynwinrt` from npm and call the API. +`dynwinrt-codegen` reads the `.winmd` metadata that ships with the Windows SDK +and WinAppSDK ahead of time. The generated JavaScript registers the required +interface signatures, and `dynwinrt` resolves and invokes the COM vtables +dynamically at runtime. There is no native build step in the consuming Electron +or Node project. The same generated bindings can work across compatible +metadata revisions without rebuilding a native addon. The runtime primarily targets **data-style WinRT APIs** (AI, storage, notifications, networking, globalization, …). It also supports WinUI `Application + Window` hosting through the generated `Application.create()` helper when the caller supplies an STA UI thread, an initialized Windows App SDK runtime, and application lifecycle. Unpackaged callers can initialize the runtime with `initWinappsdk()`; the helper resolves the framework resources from that package graph. It also enables Per-Monitor V2 DPI awareness on the UI thread. @@ -64,8 +69,8 @@ contains duplicate short names, each canonical module keeps its native symbol name while the root barrel uses a namespace-qualified name, such as `AIFoundationEmbeddingVector` or `SemanticSearchEmbeddingVector`. -Classic COM uses a separate subpath from the same package, keeping the WinRT -root API unchanged: +Classic COM is a preview under active development. It uses a separate subpath +from the same package, keeping the WinRT root API unchanged: ```js const { initializeCom } = require('@microsoft/dynwinrt/com'); @@ -83,7 +88,8 @@ type-specific cleanup function. See the repository's [Classic COM JavaScript usage guide](../../docs/guides/windows/classic-com-usage.md) for -codegen, GUID/IID/CLSID, lifetime, Automation, and `/com/unsafe` examples. +codegen, current coverage and limitations, GUID/IID/CLSID, lifetime, Automation, +and `/com/unsafe` examples. Unambiguous public WinRT activation metadata is projected as JavaScript constructors. Parameterized and composable activations support idiomatic forms such as @@ -140,7 +146,7 @@ properties, and codegen emits the paired `IVector` binding automatically. ## Platform support - **Windows 10 / 11** — x64 and arm64 native binaries shipped via `napi-rs` prebuilds -- **Node.js** ≥ 16 (Electron, plain Node, vscode extensions, …) +- **Node.js** ≥ 18 (Electron, plain Node, VS Code extensions, …) ## Links diff --git a/design.md b/design.md index 308e91fa..10d1a2f8 100644 --- a/design.md +++ b/design.md @@ -1,5 +1,13 @@ # Dynamic Projection for JavaScript and Python +> **Status: historical design record.** This document preserves the original +> motivation and alternatives considered for dynwinrt. The shipped +> implementation uses design-time generation: `dynwinrt-codegen` reads WinMD +> and emits JavaScript/TypeScript or Python wrappers, while the native runtime +> executes their registered ABI signatures. It does not lazily parse WinMD when +> an application accesses a namespace. See the root [README](README.md) and +> current [roadmap](docs/status/TODO.md) for supported behavior. + ## Objective The primary objective of this project is to expose WinRT Windows APIs to dynamic languages, specifically JavaScript and Python, while ensuring a seamless developer experience. This approach eliminates the need for native compilation (such as C++ compilers) and removes strict version coupling between the projection and the Windows App SDK (WASDK) components. @@ -8,7 +16,10 @@ The primary objective of this project is to expose WinRT Windows APIs to dynamic ### Versioning Complexity -Current static projections, such as existing PyWinRT, necessitate the generation and compilation of native code for specific versions of WinRT components. This requirement results in a complex compatibility matrix and mandates the release of new projection packages for every WASDK release, and more importantly, does not expose full WinRT APIs to developers due to AOT compilation constraints. +Static projections such as PyWinRT generate and compile native code for specific +WinRT components. This creates a compatibility matrix and requires projection +packages to track Python, architecture, Windows SDK, and Windows App SDK +releases. ### Developer Experience (DX) @@ -56,9 +67,9 @@ This infrastructure can be mostly shared across dynamic languages. This component bridges the gap between raw WinMD metadata and the runtime projection, operating in two distinct modes: -#### Mode A: Fully Lazy Assessment (Runtime) +#### Mode A: Fully Lazy Assessment (Runtime, not shipped) -In this mode, the runtime parses `.winmd` files on the fly as APIs are accessed. +This alternative would parse `.winmd` files on the fly as APIs are accessed. * **Advantages**: Proven stability in previous JavaScript projections and simpler distribution (no generation step required). * **Disadvantages**: Incurs runtime parsing overhead (potentially negligible compared to marshalling) and lacks IDE IntelliSense support. @@ -76,15 +87,19 @@ The usage workflow involves two stages: The runtime is distributed as a generic library for the target language (e.g., `npm install @microsoft/dynwinrt` or `pip install dynwinrt`). ### Step 2: Projection Usage -Developers have two options for using the projection: -1. **Direct Usage**: The runtime directly supports runtime interface specifications. Developers can use libraries directly by lazily loading namespaces with distributed WinMDs. The runtime parses the WinMDs and generates necessary interface shapes on the fly. -2. **Generated Bindings**: Alternatively, developers can execute a tool (e.g., `npx dynwinrt-codegen generate ...`) to generate bindings and types specifically for the WinMDs they intend to use. +The shipped workflow uses generated bindings. Developers run +`dynwinrt-codegen generate ...` to create wrappers and types for the WinMDs +they intend to use, then load those wrappers with the generic runtime package. +The lower-level runtime interface-registration API remains available, but no +lazy namespace/WinMD loader is shipped. ## Performance Considerations ### Overhead Analysis -The primary performance costs are attributed to WinMD parsing (in lazy mode) and the overhead of dynamic WinRT method invocation (dynamic dispatch). This invocation overhead is expected to be comparable to existing marshalling costs associated with crossing the JavaScript/Python boundary. +The shipped design-time mode removes WinMD parsing from application startup. +Runtime costs are native-language boundary conversion, ABI marshaling, and +dynamic vtable dispatch. ### Optimization Strategies @@ -158,11 +173,13 @@ HRESULT Method_Out_Pointer(void* funPtr, ComPtr self, void* outValue) { } ``` -### Known Challenges +### Original challenges and current tracking -* **Signature Casting**: Proper handling of GUID casting is required, particularly for type-safety and generics. -* **Representation Mapping**: Special handling is needed for JavaScript/Python representations; for example, `IVector` may need to map to a function rather than a simple interface instance. -* **Async Operations**: While mentioned, the handling of asynchronous operations requires robust implementation details. +Parameterized IIDs, language-native collections, async operations, delegates, +structs, nullable references, and generated type information are implemented. +Remaining correctness, coverage, lifecycle, and developer-experience work is +tracked in [`docs/status/TODO.md`](docs/status/TODO.md) and +[`docs/status/PYTHON_CHECKLIST.md`](docs/status/PYTHON_CHECKLIST.md). ## References diff --git a/docs/architecture/classic-com-support.md b/docs/architecture/classic-com-support.md index 2785b57e..0cc944e9 100644 --- a/docs/architecture/classic-com-support.md +++ b/docs/architecture/classic-com-support.md @@ -3,6 +3,12 @@ `dynwinrt` supports a deliberately limited subset of Classic COM. It is not a general Automation or native Win32 projection. +> **Status: preview, under active development.** The current CI baseline against +> `Microsoft.Windows.SDK.Win32Metadata` 71.0.14-preview is 5,567 complete safe +> interface projections out of 7,929 eligible interfaces (70.21%). Earlier +> inventory and demand-snapshot sections retain the metadata versions and dates +> stated in those sections. + For installation and application-facing examples, including GUID/IID/CLSID and `/com/unsafe`, see [Classic COM JavaScript usage](../guides/windows/classic-com-usage.md). diff --git a/docs/benchmarks/BENCHMARK.md b/docs/benchmarks/BENCHMARK.md index 90e6cda3..2fbe5a5c 100644 --- a/docs/benchmarks/BENCHMARK.md +++ b/docs/benchmarks/BENCHMARK.md @@ -1,5 +1,9 @@ # End-to-End Performance: Electron IPC +> **Recorded benchmark snapshot (August 2026).** These numbers describe the +> hardware and software environment below; they are not continuously updated. +> Re-run the command at the end of this document for current results. + Benchmark for the full Electron UI call path: **Renderer → IPC → Main Process → native addon → WinRT → IPC → Renderer**. This demonstrates that **dynwinrt has no meaningful performance impact** in real Electron applications — IPC serialization dominates all native-layer differences. diff --git a/docs/benchmarks/BENCHMARK_ANALYSIS.md b/docs/benchmarks/BENCHMARK_ANALYSIS.md index ef1eaace..c8eb83f9 100644 --- a/docs/benchmarks/BENCHMARK_ANALYSIS.md +++ b/docs/benchmarks/BENCHMARK_ANALYSIS.md @@ -1,12 +1,17 @@ # Native Layer Performance Analysis +> **Recorded benchmark snapshot (August 2026).** These measurements document a +> specific implementation and machine, not a permanent performance guarantee. +> Re-run the commands at the end of this document before making current +> performance decisions. + Benchmark for direct napi calls (no Electron IPC). Measures the actual overhead of dynwinrt's dynamic dispatch compared to static C++/WinRT projections. Environment: AMD Ryzen 9 7940HX, Windows 11, Node.js v22. All Rust builds: release + LTO + codegen-units=1. --- -## Current Performance (napi-rs standard path) +## Recorded Performance (napi-rs standard path) JS → **napi-rs** → **dynwinrt** (Rust + libffi) → COM vtable. @@ -130,7 +135,7 @@ Specialized methods that combine invoke + result extraction into a single napi c ## Theoretical Performance Limits -### Current: napi-rs macro path (~1-3 µs overhead) +### Recorded production path: napi-rs macros (~1-3 µs overhead) Our production path uses napi-rs macros for ergonomic Rust ↔ JS bindings. The napi-rs layer adds 75-170 ns per call for type checking and string roundtrips, plus each `DynWinRtValue` argument or result extraction is an extra napi boundary crossing (~500-1000 ns each). diff --git a/docs/guides/node/dev-mode.md b/docs/guides/node/dev-mode.md index d83fc578..328e051d 100644 --- a/docs/guides/node/dev-mode.md +++ b/docs/guides/node/dev-mode.md @@ -67,7 +67,9 @@ This exposes the active Node installation at `.local-node` without copying its f npx winapp manifest add-alias --name mynode.exe --manifest .\Package.appxmanifest ``` -This inserts an [``](https://learn.microsoft.com/en-us/uwp/schemas/appxpackage/uapmanifestschema/element-uap3-appexecutionalias) into the manifest, pointing at `.local-node\node.exe`. +This inserts a +[``](https://learn.microsoft.com/en-us/uwp/schemas/appxpackage/uapmanifestschema/element-uap5-appexecutionalias) +extension into the manifest, pointing at `.local-node\node.exe`. ### 3. Register the loose-layout package diff --git a/docs/guides/python/python-ui-ecosystem.md b/docs/guides/python/python-ui-ecosystem.md index bd9791f4..ade83838 100644 --- a/docs/guides/python/python-ui-ecosystem.md +++ b/docs/guides/python/python-ui-ecosystem.md @@ -1,18 +1,24 @@ # WinRT in the Python UI Ecosystem: Adoption and the Value of dynwinrt > Research snapshot: July 20, 2026 +> +> **Current project status:** since this research was collected, the +> [`dynwinrt`](https://pypi.org/project/dynwinrt/) runtime and standalone +> [`dynwinrt-codegen`](https://pypi.org/project/dynwinrt-codegen/) command have +> shipped as PyPI previews. Numerical ecosystem data below remains a dated +> research snapshot. ## What this research asks -Is there real user value in adding Python support to dynwinrt? +Is there real user value in dynwinrt's Python support? **Yes, but the value is not in creating another Python UI framework.** Python developers already build user interfaces with Qt, Tkinter, wxPython, Kivy, and pywebview. Those applications still need Windows-specific features such as notifications, media controls, OCR, Wi-Fi, Bluetooth, sensors, and -system colors. Today, they primarily access those APIs through the static -pywinrt projection. +system colors. At the time of this snapshot, they primarily accessed those APIs +through the static pywinrt projection. Public data shows that: @@ -26,8 +32,8 @@ Public data shows that: BLE, notifications, and OCR are more common. The audience for dynwinrt Python support is therefore developers who already -have a UI framework but still need Windows APIs. dynwinrt would provide the -Windows API access layer, not replace the UI framework. +have a UI framework but still need Windows APIs. dynwinrt provides the Windows +API access layer; it does not replace the UI framework. ## Terminology @@ -36,7 +42,7 @@ Windows API access layer, not replace the UI framework. | UI framework | Provides windows, controls, and UI events. Examples include PyQt, PySide, Tkinter, and wxPython. | | WinRT | A set of Windows system APIs for capabilities such as notifications, media, OCR, Bluetooth, and sensors. | | Python projection | Converts WinRT COM/ABI interfaces into ordinary Python classes, methods, and events. | -| pywinrt | The current active static Python projection. Each WinRT namespace is generated and compiled into a wheel ahead of time. | +| pywinrt | The active static Python projection at the time of this snapshot. Each WinRT namespace is generated and compiled into a wheel ahead of time. | | dynwinrt | Generates lightweight Python wrappers and invokes the WinRT ABI through a shared native runtime. | "Python UI framework" describes the API used by Python developers, not @@ -231,7 +237,7 @@ that calling WinRT from Python is not merely an experimental niche. |---|---|---| | Microsoft `winrt` | Discontinued after 2021 | Covers only CPython 3.7-3.9 and x86/x64 | | Community `winsdk` | Archived | Monolithic package supporting CPython 3.8-3.12 and ARM64 | -| Current `pywinrt` | Active solution | One `winrt-*` wheel per namespace; supports CPython 3.9-3.14 and x86/x64/ARM64 | +| `pywinrt` (July 2026) | Active solution | One `winrt-*` wheel per namespace; supports CPython 3.9-3.14 and x86/x64/ARM64 | The continued presence of all three generations shows both sustained demand and the maintenance burden of a static projection. It must track: @@ -270,7 +276,7 @@ does not require another purpose-built native extension. | Custom WinMD | Build and maintain a dedicated native projection | Use the same code generator and runtime | | Python and JavaScript | Maintain separate projection and runtime implementations | Share the Rust ABI core | | UI framework | Framework-independent | Also framework-independent | -| Current maturity | Production users and broad API coverage | Python support is still evolving; coverage depends on the runtime | +| Maturity | Production users and broad API coverage | Published preview; coverage depends on the shared runtime's supported ABI types | For an existing Python UI application, the practical value is: diff --git a/docs/guides/windows/classic-com-usage.md b/docs/guides/windows/classic-com-usage.md index dc0b0ee5..8284b73c 100644 --- a/docs/guides/windows/classic-com-usage.md +++ b/docs/guides/windows/classic-com-usage.md @@ -3,6 +3,13 @@ This guide explains how to use `dynwinrt` to call Classic COM from Node.js/Electron and how to correctly handle GUIDs, IIDs, CLSIDs, and REFIIDs. +> **Status: preview, under active development.** Generated bindings are +> available for interfaces whose complete ABI, layout, ownership, and cleanup +> contracts are validated. Unsupported interfaces fail closed instead of +> emitting a partial wrapper. See +> [Classic COM support](../../architecture/classic-com-support.md) for the +> current coverage baseline and known gaps. + > Prefer the safe bindings generated by `dynwinrt-codegen`. Use `@microsoft/dynwinrt/com/unsafe` only when the > metadata cannot fully describe the ABI and you have verified every calling convention against the native headers > and Microsoft documentation. diff --git a/docs/guides/windows/msix-packaging.md b/docs/guides/windows/msix-packaging.md index 50cb91a8..13da25f0 100644 --- a/docs/guides/windows/msix-packaging.md +++ b/docs/guides/windows/msix-packaging.md @@ -2,7 +2,7 @@ This guide shows how to package a Node.js application that uses `@microsoft/dynwinrt` into an MSIX with -[WinApp CLI](https://github.com/microsoft/WinAppCli) 0.5.0. +[WinApp CLI](https://github.com/microsoft/WinAppCli) 0.6.2. The process first creates an application-specific Node [Single Executable Application (SEA)](https://nodejs.org/api/single-executable-applications.html). @@ -20,7 +20,7 @@ Create a Node.js project: mkdir my-dynwinrt-app cd my-dynwinrt-app npm init -y -npm install --save-dev @microsoft/winappcli@0.5.0 +npm install --save-dev @microsoft/winappcli@0.6.2 npx winapp init . --use-defaults --add-js-bindings ``` @@ -322,7 +322,7 @@ For ARM64, repeat the SEA build with the same Node version's [`win-arm64/node.exe`](https://nodejs.org/dist/v24.19.0/win-arm64/node.exe) and the ARM64 dynwinrt runtime. -WinApp CLI 0.5.0 can create a multi-architecture bundle directly: +WinApp CLI 0.6.2 can create a multi-architecture bundle directly: ```powershell npx winapp pack ` diff --git a/docs/status/PYTHON_CHECKLIST.md b/docs/status/PYTHON_CHECKLIST.md index e22ec718..c4540da6 100644 --- a/docs/status/PYTHON_CHECKLIST.md +++ b/docs/status/PYTHON_CHECKLIST.md @@ -1,7 +1,8 @@ # Python readiness checklist -This checklist tracks the path from the current source-built Python prototype -to a distributable, typed, and reliable WinRT projection. +This checklist records the shipped Python preview and tracks the remaining work +toward a stable, broadly supported WinRT projection. The `dynwinrt` runtime and +standalone `dynwinrt-codegen` command are published on PyPI. See [`docs/guides/python/python-ui-ecosystem.md`](../guides/python/python-ui-ecosystem.md) for research on Python UI frameworks, static pywinrt adoption, real integrations, and the value @@ -9,13 +10,15 @@ of a dynamic projection. ## Target states -- **Data API preview:** a clean machine can install wheels and generated +- **Data API preview (shipped):** a clean machine can install wheels and generated bindings, then call supported Windows SDK APIs without Rust, Node.js, or a source checkout. -- **Data API release:** generated APIs follow normal Python semantics for +- **Data API release (in progress):** generated APIs follow normal Python semantics for typing, async, events, collections, errors, and lifecycle. -- **WinUI preview:** Python can bootstrap the Windows App SDK, enter an STA, - construct composable WinUI classes, load Fluent resources, and close cleanly. +- **WinUI preview (x64 validated):** Python can bootstrap the Windows App SDK, + enter an STA, construct composable WinUI classes, and load Fluent resources. + Native ARM64 immediate teardown remains tracked in + [issue #116](https://github.com/microsoft/dynwinrt/issues/116). ## Verified baseline @@ -24,7 +27,7 @@ of a dynamic projection. APIs on ARM64. - [x] Python generation emits `.py` implementations. - [x] `--lang py` emits `.pyi`, `__init__.pyi`, and `py.typed` by default. -- [x] Generated Python E2E covers 34 Windows SDK scenarios. +- [x] Generated Python E2E covers 42 API specs and 88 checks. - [x] Runtime primitives exist for arrays, structs, delegates, events, cancellation, progress callbacks, vectors, and maps. - [x] Python codegen snapshots cover the `Uri` implementation and stubs. @@ -147,7 +150,7 @@ of a dynamic projection. Windows App SDK, and custom WinMD namespaces. - [x] Add runnable samples for files, notifications, imaging, async, events, collections, and custom WinMD consumption. -- [ ] Document generated-code version compatibility with `dynwinrt`. +- [x] Document generated-code version compatibility with `dynwinrt`. - [ ] Add troubleshooting for metadata, apartment, bootstrap, architecture, and wheel compatibility failures. - [x] Add progress-callback tests for worker-thread delivery and operations @@ -225,14 +228,14 @@ of a dynamic projection. 20. [x] Make reference returns null-safe without lying in generated annotations. 21. [x] Preserve `UInt32` / `UInt64` values across the Python boundary. 22. [x] Project and box `IReference` struct fields, including struct-valued `T`. -22. [x] Add typed event arguments while preserving token subscriptions and adding +23. [x] Add typed event arguments while preserving token subscriptions and adding idempotent unsubscribe helpers. -23. [x] Project public composable constructors and reject protected composition. -24. [x] Add an experimental, typed WinUI `Application` bootstrap path backed +24. [x] Project public composable constructors and reject protected composition. +25. [x] Add an experimental, typed WinUI `Application` bootstrap path backed by a shared `codegen/winrt/extensions/winui` spec consumed by both JavaScript and Python projection. -25. [x] Run a real unpackaged x64 Python WinUI app with Fluent resources, +26. [x] Run a real unpackaged x64 Python WinUI app with Fluent resources, Window/Grid/Button/TextBlock, automation-driven Click, and clean apartment shutdown. -26. [x] Release the GIL around blocking WinUI host calls and verify asyncio +27. [x] Release the GIL around blocking WinUI host calls and verify asyncio worker progress, WinRT async completion, and DispatcherQueue UI dispatch. diff --git a/docs/status/TODO.md b/docs/status/TODO.md index 72fc1854..3a134031 100644 --- a/docs/status/TODO.md +++ b/docs/status/TODO.md @@ -8,19 +8,15 @@ _None currently. Reserved for issues that make v0.1 unshippable (crash on happy ## P1 — Correctness / quality (near-term) -- [ ] **Complete the first native Python ARM64 release-matrix run**. The - fail-closed wheel workflow targets the existing - `[self-hosted, Windows, ARM64, winui]` runner for CPython 3.11–3.14, but this - worktree can validate only x64. Do not mark ARM64 wheels releasable until all - native consumer jobs have imported them and called `Windows.Foundation.Uri`. - -- [ ] **Panic-free COM entrypoints**. Several `extern "system"` COM callbacks still `unwrap()` on raw pointer inputs, which is UB across the FFI boundary if a caller passes a bad pointer: - - `crates/dynwinrt/src/delegate.rs:309` — `IUnknown::from_raw_borrowed(&raw).unwrap()` inside `marshal_abi_ptr` (fires whenever WinRT passes a null pointer arg to a delegate; not just malicious callers) - - `crates/dynwinrt/src/com_helpers.rs:42, 53` — same pattern in `com_to_usize` / `com_usize_addref_out` - - `crates/dynwinrt/src/array.rs:288, 461` — array element COM read paths - - `crates/dynwinrt/src/com_helpers.rs:74-103` — generated `IInspectable` stubs write through `*count`, `*iids`, `*name`, `*level` without null-checking the out-pointer - - `crates/dynwinrt/src/vector.rs:229, 382, 384` — `get_at`, `get_many`, `get_size` write to `result`/`items_out`/`actual` unconditionally - - `crates/dynwinrt/src/map.rs:222, 231, 267, 396` — `lookup`, `size`, `insert`, `split` do the same +- [ ] **Panic-free WinRT collection entrypoints**. Several internal + `extern "system"` implementations still assume Windows supplied valid + pointers: + - `com_to_usize` / `com_usize_addref_out` and array clone/read paths use + `IUnknown::from_raw_borrowed(...).unwrap()` after a non-null check; + - generated `IInspectable` stubs still write through output pointers without + validating them; and + - vector/map/iterator methods still have output writes whose `E_POINTER` + coverage must be audited method by method. Fix pattern: at every COM ABI entry, validate each out-pointer against null and return `E_POINTER`; convert `.unwrap()` on incoming COM pointers to `Result` + `E_UNEXPECTED`. @@ -40,7 +36,10 @@ _None currently. Reserved for issues that make v0.1 unshippable (crash on happy validate type, numeric range, and nested struct identity before entering core accessors. -- [ ] **Codegen: `extract_iid` silently zero-fills malformed GuidAttribute**. `tools/dynwinrt-codegen/src/meta.rs:1030-1051` — if any GuidAttribute field is the wrong integer width, helpers return `0`, producing a plausible-but-wrong IID that will corrupt interface registration without any error. Treat non-matching shapes as a hard error / empty IID. +- [ ] **Codegen: `extract_iid` silently zero-fills malformed GuidAttribute**. + `extract_u8`/`extract_u16`/`extract_u32` return `0` for a mismatched + metadata value, producing a plausible-but-wrong IID. Treat a malformed + attribute as a hard error or empty IID. - [x] **Codegen: project concrete generic ancestor interfaces**. Inherited generic interfaces are resolved with their concrete arguments, deduplicated by full @@ -52,9 +51,10 @@ _None currently. Reserved for issues that make v0.1 unshippable (crash on happy Python control subclasses by arbitrary qualified names and preserves native overrides/identity. OS activation remains deliberately outside this boundary. -- [ ] **Codegen: default-interface lookup returns first hit**. `tools/dynwinrt-codegen/src/meta.rs:1075-1090` — `find_default_interface_iid` returns on the first `DefaultAttribute` it resolves, which may not be the actual default in edge cases with malformed metadata. Validate against parsed default interface metadata or fail loudly. - -- [ ] **Codegen: `--class-name` docs vs `--class` CLI**. The CLI derives the flag from the field name (`class_name` → `--class-name`), and docs use `--class-name`. Confirm both are wired consistently and that any lingering `--class` example is updated. (One instance in `main.rs` after_help was fixed in this review round.) +- [ ] **Codegen: default-interface lookup returns first hit**. + `find_default_interface_type` returns the first `DefaultAttribute` it + resolves. Validate that malformed metadata cannot expose multiple + conflicting defaults, or fail loudly. - [ ] **Codegen: snapshot coverage too narrow**. Python snapshots now cover `Windows.Foundation.Uri` and the method-rich @@ -62,8 +62,6 @@ _None currently. Reserved for issues that make v0.1 unshippable (crash on happy interfaces, and inherited-interface flattening still need dedicated snapshots. -- [ ] **Rust: `AppendOnlyBoxArena::stable_ptr` panics on out-of-range**. `crates/dynwinrt/src/metadata_table/append_only_arena.rs:45-49` — trusted internal use, but the invariant is undocumented and callers can drift. Add a documented safety contract and a debug assertion (or return `Option`). - - [ ] **Rust: map key semantics under-specified**. `crates/dynwinrt/src/map.rs:79-120` — pointer identity is the default, with an ad-hoc string extraction path for `IPropertyValue`. Define one contract (identity vs value equality) and enforce it explicitly. - [x] **JS: same-thread delegate N-API status handling**. Global lookup, @@ -72,14 +70,10 @@ _None currently. Reserved for issues that make v0.1 unshippable (crash on happy HRESULT when dispatch cannot complete. Each delegate also carries a `napi_async_context`, preserving `async_hooks` and `AsyncLocalStorage`. -- [ ] **JS: `DynWinRtStruct::set_object` silently no-ops**. `bindings/js/src/lib.rs:1103-1125` — unsupported input kinds hit `_ => {}`. Return `napi::Result<()>` with a clear error. - ## P2 — Feature completeness - [ ] **Struct auto-marshaling**. Users still need `DynWinRtStruct.create()` + `setF64(...)` per field. Codegen generates `_packXxx` helpers for known structs already; the gap is user-defined / ad-hoc structs. Consider generic `pack(schema, obj)`. -- [ ] **Nullable / `IReference` handling**. Null COM pointers surface as `WinRTValue::Null`; codegen wrappers should surface `T | null` in `.d.ts` for these return positions. - - [x] **Python `IReference` as struct field**. Generated structs read native `T | None`, accept native values and legacy wrappers, and box through `DynWinRTStruct.set_object`; covered by SDK `HttpProgress` and synthetic @@ -93,32 +87,45 @@ _None currently. Reserved for issues that make v0.1 unshippable (crash on happy ## P3 — Developer experience & performance -- [ ] **Auto-detect WinAppSDK Bootstrap DLL for unpackaged apps**. `initialize_winappsdk(major, minor)` currently `.expect(...)`s the `WINAPPSDK_BOOTSTRAP_DLL_PATH` env var (`crates/dynwinrt/src/winapp.rs:43`). Only relevant when a user is running unpackaged (packaged/MSIX apps don't call this — the framework package dep loads WinAppSDK automatically). For the unpackaged path, search `~/.winapp/packages/`, `~/.nuget/packages/microsoft.windowsappsdk.*/`, and standard Program Files install paths, in that order, falling back to the env var. Also swap the `expect(...)` for a typed error. +- [ ] **Auto-detect the WinAppSDK Bootstrap DLL for unpackaged apps**. + Initialization now returns a typed error when neither + `bootstrap_dll_path` nor `WINAPPSDK_BOOTSTRAP_DLL_PATH` is supplied, but + it does not search restored `~/.winapp/packages`, + `~/.nuget/packages/microsoft.windowsappsdk.*`, or installed framework + locations. -- [ ] **Error message enrichment**. Wrap HRESULT errors with `IRestrictedErrorInfo` message strings on the way out; today users see raw HRESULT codes. +- [ ] **JavaScript error message enrichment**. Preserve restricted WinRT error + information alongside HRESULTs. Python already exposes the signed HRESULT + through `.winerror` and includes restricted error text when Windows + provides it. - [ ] **Value-type inputs to `invoke()`**. `invoke()` currently requires `DynWinRtValue` wrappers per argument (`+~0.6-1.6 µs / arg`). Accept raw JS values (`number`/`string`/`bool`) and dispatch via `in_param_types()` on `MethodHandle`. -- [ ] **Method handle without `RwLock`**. `invoke_method` takes an `RwLock` read on every call (~15-20 ns). Store `Arc` directly in `MethodHandle` and bypass the arena lock on the hot path. +- [ ] **Method handle without an arena read lock**. `MethodHandle` stores an + arena index; each call briefly reads `AppendOnlyBoxArena` to obtain its + stable method pointer. Store a stable method handle directly if benchmark + results justify removing that lock. - [ ] **Stack-allocated return path**. `Ok(vec![out])` heap-allocates per call. `SmallVec<[WinRTValue; 2]>` for the common single-out shape. -- [ ] **JS binding: raw `Env` lifetime discipline**. `bindings/js/src/lib.rs:1400-1412` — the same-thread delegate path stores the raw `napi_env` under the assumption that the registering thread stays alive. Document + assert thread affinity, or minimize raw-env lifetime. - -- [ ] **JS: `HSTRING` field extraction via layout cast**. `bindings/js/src/lib.rs:1041-1049` — reads HSTRING out of `ValueTypeData` by reinterpreting bytes as `*const HSTRING`. Expose a typed accessor in `dynwinrt` (`ValueTypeData::field_hstring(index)`) and switch the JS side to it. - -- [ ] **`package.json` engines vs README floor**. `bindings/js/package.json:34-36` advertises Node 12+ ranges, README says Node ≥16. Align to whichever floor CI actually tests. (Currently CI runs Node 24.) +- [ ] **JS binding: raw `Env` lifetime discipline**. The same-thread delegate + path stores the raw `napi_env` under the assumption that the registering + thread stays alive. Document and assert thread affinity, or minimize the + raw environment lifetime. -- [ ] **Python binding follow-ups**. The runtime and codegen now cover async, - collections, structs, typed delegates/events, nullable references, and an - experimental WinUI Application bootstrap. Remaining work is tracked in - `PYTHON_CHECKLIST.md`, especially generated package layout, CPython/architecture - coverage, native XAML custom-control registration/overrides, object identity, - and delegates with more than two ABI parameters. +- [ ] **`package.json` engines vs README floor**. `bindings/js/package.json` + advertises Node 12+ ranges, while the README requires Node 18+. Align both + to a tested release floor. (Currently CI runs Node 24.) -- [ ] **Troubleshooting docs in READMEs**. Common failure modes not covered end-to-end: `WINAPPSDK_BOOTSTRAP_DLL_PATH` not set, mismatched apartment, missing capability. Root `README.md` has a small table; grow it based on the last three GitHub issues that repeated. +- [ ] **Python binding follow-ups**. Remaining work is tracked in + `PYTHON_CHECKLIST.md`: WinApp CLI integration, consolidated + troubleshooting, native ARM64 WinUI E2E, delegates with more than two ABI + parameters, zero-copy buffers, and diagnostics. -- [ ] **JSDoc / TSDoc on generated `.d.ts`**. Parameter descriptions and return descriptions are missing on many generated method signatures. `xml_doc.rs` already loads sibling `.xml` — thread that through render_dts. +- [ ] **Consolidate troubleshooting docs**. Apartment, bootstrap, package + identity, architecture, and capability guidance exists across the root, + Python, Node dev-mode, and sample READMEs; add one indexed troubleshooting + guide instead of duplicating it further. ## Completed @@ -133,6 +140,8 @@ Kept for reference; git history is the source of truth. Grouped by area. - [x] `toNumber()` expanded to Bool, I8, U8, I16, U16, I32, U32, HResult - [x] `WinGuid.toString()` for cache keys - [x] Auto value wrapping — `filter.append('.png')` works directly on generated `IVector_String` +- [x] `DynWinRtStruct::setObject` validates field kind and value type and returns + a contextual N-API error instead of silently ignoring invalid values ### Runtime (crates/dynwinrt) - [x] `SingleThreadedVector` / `SingleThreadedMap` migrated `RefCell` → `Mutex`; now `Send + Sync + IAgileObject` @@ -147,6 +156,9 @@ Kept for reference; git history is the source of truth. Grouped by area. - [x] COM vtable panic safety: `lock_or!` + null-checked `from_raw_borrowed` returning HRESULTs - [x] `WinRTValue::Enum { value, type_handle }` as independent runtime type - [x] Parameterized type `default_winrt_value` no longer panics +- [x] `AppendOnlyBoxArena` documents and tests its stable-pointer invariant; + method calls release the arena read guard before native dispatch +- [x] JS HSTRING struct fields use typed core accessors instead of layout casts ### Metadata / codegen - [x] Struct helpers deduplicated (`generate_struct_helpers`: shared TS interface + pack/unpack) @@ -158,6 +170,8 @@ Kept for reference; git history is the source of truth. Grouped by area. - [x] Parameterized interfaces (e.g. `IVector`, `IReference`) generated as concrete types from winmd (removed unused `_collections.ts`) - [x] Auto-detect `Windows.winmd` from `C:\Program Files (x86)\Windows Kits\10\UnionMetadata\` - [x] Collection methods: IVector / IVectorView / IMap / IMapView / IKeyValuePair / IIterable / IIterator with full methods +- [x] Generated JSDoc includes summaries, parameter descriptions, return + descriptions, and deprecation text from sibling XML documentation ### Features - [x] Delegate / event support: COM vtable + napi ThreadsafeFunction in `delegate.rs`; `DynWinRtDelegate.create(iid, paramTypes, callback)`; same-thread synchronous invocation path @@ -166,9 +180,10 @@ Kept for reference; git history is the source of truth. Grouped by area. ### Distribution / CI - [x] Python runtime wheel matrix for CPython 3.11–3.14 on x64/native ARM64, standalone `py3-none-win_` codegen wheels, isolated artifact consumers, - GitHub release assets, and manual OIDC trusted-publishing gates + shared GitHub release assets, and PyPI publication through Microsoft ESRP - [x] npm prebuilds for `win32-x64-msvc` + `win32-arm64-msvc` -- [x] `.github/workflows/build.yml` builds winrt-meta and dynwinrt-js on x64 + arm64, plus publishing and sample generation +- [x] `.github/workflows/build.yml` validates the Rust runtime, JS/Python + bindings, codegen, Classic COM coverage, and x64/ARM64 targets - [x] `winapp init --add-js-bindings` toolchain integration - [x] `package.json` repository URL corrected to `github.com/microsoft/dynwinrt` - [x] Cargo.toml files have `authors`, `license`, `description`, `repository`; `bindings/py/pyproject.toml` has authors/license/urls diff --git a/samples/python/README.md b/samples/python/README.md index 02aabcf1..cab5cd01 100644 --- a/samples/python/README.md +++ b/samples/python/README.md @@ -1,7 +1,8 @@ # Python samples -All Python samples use generated bindings and the local `dynwinrt` runtime. -Run each sample's `generate.ps1` before `run.ps1`. +All Python samples use generated bindings and an installed `dynwinrt` runtime. +Install `dynwinrt` and `dynwinrt-codegen` from PyPI, or build both from this +checkout, then run each sample's `generate.ps1` before `run.ps1`. | Sample | Demonstrates | | --- | --- | diff --git a/samples/python/winui-tic-tac-toe-code-only/README.md b/samples/python/winui-tic-tac-toe-code-only/README.md index 3c68d230..879a45ba 100644 --- a/samples/python/winui-tic-tac-toe-code-only/README.md +++ b/samples/python/winui-tic-tac-toe-code-only/README.md @@ -14,38 +14,35 @@ returned object as the projected `SystemBackdrop` expected by ## Prerequisites -- Windows 11 on x64 with Python and Rust/Cargo available. +- Windows 11 on x64 with CPython 3.11–3.14. - An unpackaged **x64** WinAppSDK 2.3 fixture: `Microsoft.UI.Xaml.winmd`, a newline-separated reference-WinMD list, and the matching x64 `Microsoft.WindowsAppRuntime.Bootstrap.dll`. The matching x64 WinAppSDK framework/runtime packages and resources must also be installed or available to the unpackaged runtime. - `dynwinrt` installed in the Python interpreter used to run the sample. -- A compatible `dynwinrt-codegen` executable, either on `PATH` or passed with - `-Codegen`. +- Matching `dynwinrt` and `dynwinrt-codegen` versions. -From the repository root, build codegen and install the Python runtime: +Install the published preview packages: ```powershell -cargo build -p dynwinrt-codegen --release -Push-Location bindings\py -python -m pip install maturin -python -m maturin develop --release -Pop-Location +python -m pip install --pre dynwinrt dynwinrt-codegen ``` +For source-checkout development, build `dynwinrt-codegen` and install the +runtime with `python -m maturin develop --release` from `bindings\py` instead. + Generate the local projection package and copy the bootstrap DLL: ```powershell .\generate.ps1 ` -WinuiWinmd C:\fixtures\winappsdk\metadata\Microsoft.UI.Xaml.winmd ` -RefList C:\fixtures\winappsdk\winmd-reference-list.txt ` - -BootstrapDll C:\fixtures\winappsdk\x64\Microsoft.WindowsAppRuntime.Bootstrap.dll ` - -Codegen ..\..\..\target\release\dynwinrt-codegen.exe + -BootstrapDll C:\fixtures\winappsdk\x64\Microsoft.WindowsAppRuntime.Bootstrap.dll ``` -If codegen is installed on `PATH`, omit `-Codegen`. Run with the Python -environment that contains `dynwinrt`: +Pass `-Codegen ..\..\..\target\release\dynwinrt-codegen.exe` when testing a +source build. Run with the Python environment that contains `dynwinrt`: ```powershell .\run.ps1 -Python C:\path\to\python.exe diff --git a/samples/python/winui-tic-tac-toe/README.md b/samples/python/winui-tic-tac-toe/README.md index 30313763..a6cfb2aa 100644 --- a/samples/python/winui-tic-tac-toe/README.md +++ b/samples/python/winui-tic-tac-toe/README.md @@ -7,27 +7,24 @@ window resizing, a named Python `TicTacToePanel` XAML registration, a native ## Prerequisites -- Windows 11 on x64 with Python and Rust/Cargo available. +- Windows 11 on x64 with CPython 3.11–3.14. - An unpackaged **x64** WinAppSDK 2.3 fixture: `Microsoft.UI.Xaml.winmd`, a newline-separated reference-WinMD list, and the matching x64 `Microsoft.WindowsAppRuntime.Bootstrap.dll`. The matching x64 WinAppSDK framework/runtime packages and resources must also be installed or available to the unpackaged runtime. - `dynwinrt` installed in the Python interpreter used to run the sample. -- A compatible `dynwinrt-codegen` executable, either on `PATH` or passed with - `-Codegen`. +- Matching `dynwinrt` and `dynwinrt-codegen` versions. -No published package is assumed. From the repository root, build the codegen -executable and install the runtime into the active Python environment: +Install the published preview packages: ```powershell -cargo build -p dynwinrt-codegen --release -Push-Location bindings\py -python -m pip install maturin -python -m maturin develop --release -Pop-Location +python -m pip install --pre dynwinrt dynwinrt-codegen ``` +For source-checkout development, build `dynwinrt-codegen` and install the +runtime with `python -m maturin develop --release` from `bindings\py` instead. + From this sample directory, generate the local package and copy the bootstrap DLL (replace the fixture paths): @@ -35,12 +32,11 @@ DLL (replace the fixture paths): .\generate.ps1 ` -WinuiWinmd C:\fixtures\winappsdk\metadata\Microsoft.UI.Xaml.winmd ` -RefList C:\fixtures\winappsdk\winmd-reference-list.txt ` - -BootstrapDll C:\fixtures\winappsdk\x64\Microsoft.WindowsAppRuntime.Bootstrap.dll ` - -Codegen ..\..\..\target\release\dynwinrt-codegen.exe + -BootstrapDll C:\fixtures\winappsdk\x64\Microsoft.WindowsAppRuntime.Bootstrap.dll ``` -If the CLI is installed on `PATH`, omit `-Codegen`. Run with the same Python -environment that contains `dynwinrt`: +Pass `-Codegen ..\..\..\target\release\dynwinrt-codegen.exe` when testing a +source build. Run with the same Python environment that contains `dynwinrt`: ```powershell .\run.ps1 -Python C:\path\to\python.exe diff --git a/tools/dynwinrt-codegen/E2E_TEST.md b/tools/dynwinrt-codegen/E2E_TEST.md index b949e28f..2668728a 100644 --- a/tools/dynwinrt-codegen/E2E_TEST.md +++ b/tools/dynwinrt-codegen/E2E_TEST.md @@ -1,6 +1,9 @@ # End-to-End Test: FileOpenPicker -This guide walks through a full end-to-end test of the dynwinrt-codegen pipeline, from cloning the repo to opening a file picker dialog. The codegen emits plain ESM JavaScript (`.js`) plus ambient TypeScript declarations (`.d.ts`), so the same generated output works from both `node` and `tsx`. +This guide walks through a full end-to-end test of the dynwinrt-codegen +pipeline, from cloning the repo to opening a file picker dialog. Codegen emits +CommonJS implementation modules (`.js`), ESM facades (`.mjs`), and ambient +TypeScript declarations (`.d.ts`). ## Prerequisites @@ -29,6 +32,7 @@ cargo build -p dynwinrt-codegen --release # Build the JS native binding cd bindings/js +npm install npm run build cd ../.. ``` @@ -46,6 +50,9 @@ Create `package.json`: "private": true, "dependencies": { "@microsoft/dynwinrt": "file:../../dynwinrt/bindings/js" + }, + "devDependencies": { + "tsx": "^4.21.0" } } ``` @@ -56,7 +63,7 @@ npm install ## Step 3: Generate bindings -Windows SDK `Windows.winmd` is auto-detected from `C:\Program Files (x86)\Windows Kits\10\UnionMetadata\`. Only the target WinAppSDK winmd needs to be specified. `--lang js` is the default and emits `.js` plus `.d.ts`: +Windows SDK `Windows.winmd` is auto-detected from `C:\Program Files (x86)\Windows Kits\10\UnionMetadata\`. Only the target WinAppSDK winmd needs to be specified. `--lang js` is the default and emits CommonJS `.js`, ESM `.mjs` facades, and `.d.ts`: ```bash cd ../../dynwinrt @@ -68,18 +75,21 @@ cargo run -p dynwinrt-codegen --release -- generate \ --output ../test-winmd/test-picker/generated ``` -Each generated symbol produces both a `.js` module and a matching `.d.ts` (e.g. `FileOpenPicker.js` + `FileOpenPicker.d.ts`), plus an `index.js` / `index.d.ts` re-exporting everything. +Each generated symbol produces both a CommonJS `.js` module and a matching +`.d.ts` (for example, `FileOpenPicker.js` + `FileOpenPicker.d.ts`). The package +also contains CommonJS `index.js`, ESM `index.mjs`, and `index.d.ts` facades. Parameterized collection interfaces (e.g. `IVector`) are automatically instantiated from `Windows.winmd` as concrete types like `IVector_String.js` / `.d.ts`. ## Step 4: Write test script -Create `test_picker.ts` in the test project (TypeScript here — the same imports work from plain `.js` too, since the generated modules are ESM JavaScript with adjacent `.d.ts` declarations): +Create `test_picker.ts` in the test project. `tsx` reads the adjacent +declarations and interoperates with the generated CommonJS modules: ```typescript import { initWinappsdk, roInitialize, DynWinRtValue } from '@microsoft/dynwinrt' -import { FileOpenPicker } from './generated/windows/storage/pickers/FileOpenPicker.js' -import { PickerViewMode } from './generated/windows/storage/pickers/PickerViewMode.js' +import { FileOpenPicker } from './generated/microsoft/windows/storage/pickers/FileOpenPicker.js' +import { PickerViewMode } from './generated/microsoft/windows/storage/pickers/PickerViewMode.js' async function main() { initWinappsdk(1, 8) @@ -109,7 +119,7 @@ async function main() { // Open file picker dialog console.log('Opening file picker dialog...') const result = await picker.pickSingleFileAsync() - if (result && result._obj) { + if (result) { console.log('Selected file path:', result.path) } else { console.log('User cancelled the picker') @@ -150,14 +160,23 @@ A file picker dialog will open. Select a file (filtered to .png/.jpg/.txt) to co |---|---| | **dynwinrt-codegen** | Generates correct interface registrations, method signatures, factory methods, enum values from `.winmd` metadata | | **dynwinrt-codegen (generics)** | Parameterized interfaces (IVector\, IVectorView\) instantiated from `Windows.winmd` with concrete types, auto-detected Windows SDK path | -| **dynwinrt (Rust)** | Dynamic COM vtable dispatch, parameterized type out-params, async operation (IAsyncOperation), RawPtr out-buffer for COM pointers | +| **dynwinrt (Rust)** | Dynamic COM vtable dispatch, parameterized type outputs, and `IAsyncOperation` | | **@microsoft/dynwinrt (napi)** | JS-to-Rust bridge: `invoke()`, `toPromise()`, `toNumber()`, `toString()`, type marshalling | | **WinAppSDK runtime** | Bootstrap initialization, FileOpenPicker activation factory, IFileOpenPickerFactory.CreateInstance | | **Collection types** | `IVector_String.append()`, `.size`, `.getAt()` — from winmd parameterized interface instantiation, not hardcoded | -## Additional E2E tests +## Automated E2E suite + +The repository's canonical cross-language specs are in +[`tests/e2e/e2e_specs.json`](../../tests/e2e/e2e_specs.json). The orchestrator +generates temporary bindings and runs the JavaScript/TypeScript, Python, or +Classic COM runners. From the repository root: + +```powershell +.\tests\e2e\e2e_test.ps1 -Lang ts +.\tests\e2e\e2e_test.ps1 -Lang py +.\tests\e2e\e2e_test.ps1 -Lang com +``` -| Test | Namespace | What it covers | -|---|---|---| -| **test-http** | `Windows.Foundation` + `Windows.Web.Http` | Uri properties, HttpClient.getStringAsync (async with progress), response status code, content.readAsStringAsync | -| **test-geo** | `Windows.Devices.Geolocation` | Struct pass-by-value (BasicGeoposition → Geopoint.create), struct out-param (Geopoint.position) | +The Classic COM suite also requires `DYNWINRT_WIN32_WINMD` or an installed +`Microsoft.Windows.SDK.Win32Metadata` package. diff --git a/tools/dynwinrt-codegen/README.md b/tools/dynwinrt-codegen/README.md index 710aba30..82975a35 100644 --- a/tools/dynwinrt-codegen/README.md +++ b/tools/dynwinrt-codegen/README.md @@ -53,7 +53,7 @@ package. | `--class-name NAME[,NAME...]` | Generate specific classes or public interfaces. Use fully qualified names, or unqualified names together with `--namespace`. | | `--ref PATH[;PATH...]` | Metadata used only for type resolution. Sibling discovery is disabled for references. | | `--ref-list FILE` | Newline-separated reference metadata paths; blank lines and `#` comments are ignored. | -| `--lang js\|py` | `js` emits ESM `.js` and `.d.ts` files (default); `py` emits `.py`, `.pyi`, and `py.typed`. | +| `--lang js\|py` | `js` emits CommonJS `.js`, an ESM facade, and `.d.ts` files (default); `py` emits `.py`, `.pyi`, and `py.typed`. | | `--output DIR` | Dedicated codegen-owned output directory (default `./generated`). Existing contents may be replaced or removed. | | `--import-name NAME` | Runtime package imported by generated JavaScript (default `@microsoft/dynwinrt`). | | `--dry-run` | Validate metadata, dependencies, ABI contracts, and layout without writing files. | @@ -112,9 +112,10 @@ WinRT output includes typed classes and interfaces, public activation constructors, static factory methods, enums, structs, delegates, async operations, and generic collections. -JavaScript output is ESM and needs no TypeScript compilation step. Python output -uses snake_case names and includes type information by default. Documentation -from sibling XML files is included when available. +JavaScript implementation modules are CommonJS, with `index.mjs` facades for +ESM consumers, and need no TypeScript compilation step. Python output uses +snake_case names and includes type information by default. Documentation from +sibling XML files is included when available. Classic COM generation is available only with `--lang js`. It is isolated in a `com` subpackage and fails closed when metadata does not provide enough ABI, diff --git a/tools/dynwinrt-codegen/TYPE_COVERAGE.md b/tools/dynwinrt-codegen/TYPE_COVERAGE.md index 81f1e951..3b90b774 100644 --- a/tools/dynwinrt-codegen/TYPE_COVERAGE.md +++ b/tools/dynwinrt-codegen/TYPE_COVERAGE.md @@ -1,252 +1,139 @@ -# Type Coverage & Implementation +# WinRT type coverage -This document describes how each WinRT type is handled across the three layers: -**codegen** (tools/dynwinrt-codegen), **JS binding** (bindings/js), and **core runtime** (crates/dynwinrt). +This document summarizes the current language projections across: -## Overview +- the shared Rust ABI runtime in `crates/dynwinrt`; +- the JavaScript N-API binding in `bindings/js`; +- the Python PyO3 binding in `bindings/py`; and +- the JavaScript/TypeScript and Python generators in + `tools/dynwinrt-codegen`. -The codegen reads WinRT metadata (.winmd) and generates JavaScript bindings with ambient TypeScript declarations (`.d.ts`). Each WinRT type needs to be handled in four directions: +Classic COM has a separate semantic type system and safety boundary. See +[Classic COM support](../../docs/architecture/classic-com-support.md) instead +of applying the WinRT mappings below to `Windows.Win32.winmd`. -1. **Method parameter** (JS -> WinRT): `wrap_arg()` wraps JS value into `DynWinRtValue` -2. **Method return** (WinRT -> JS): `convert_return()` extracts JS value from `DynWinRtValue` -3. **Struct field read** (WinRT -> JS): `struct_field_getter()` reads from `DynWinRtStruct` -4. **Struct field write** (JS -> WinRT): `struct_field_setter()` writes to `DynWinRtStruct` +## Scalar and foundation types -Plus two annotation functions: `ts_param_type()` and `ts_return_type()` for TypeScript type signatures. - ---- - -## Primitive Types - -| WinRT Type | TS Type | wrap_arg | convert_return | Struct getter | Struct setter | -|---|---|---|---|---|---| -| Boolean | `boolean` | `boolValue(x)` | `.toBool()` | `getU8(i) !== 0` | `setU8(i, x ? 1 : 0)` | -| Int8 | `number` | `i32(x)` | `.toNumber()` | `getI8(i)` | `setI8(i, x)` | -| UInt8 | `number` | `i32(x)` | `.toNumber()` | `getU8(i)` | `setU8(i, x)` | -| Int16 | `number` | `i32(x)` | `.toNumber()` | `getI16(i)` | `setI16(i, x)` | -| UInt16 | `number` | `i32(x)` | `.toNumber()` | `getU16(i)` | `setU16(i, x)` | -| Char16 | `number` | `i32(x)` | `.toNumber()` | `getU16(i)` | `setU16(i, x)` | -| Int32 | `number` | `i32(x)` | `.toNumber()` | `getI32(i)` | `setI32(i, x)` | -| UInt32 | `number` | `i32(x)` | `.toNumber()` | `getU32(i)` | `setU32(i, x)` | -| Int64 | `number` | `i64(x)` | `.toI64()` | `getI64(i)` | `setI64(i, x)` | -| UInt64 | `number` | `i64(x)` | `.toI64()` | `getU64(i)` | `setU64(i, x)` | -| Single | `number` | `f32(x)` | `.toF64()` | `getF32(i)` | `setF32(i, x)` | -| Double | `number` | `f64(x)` | `.toF64()` | `getF64(i)` | `setF64(i, x)` | - -### Notes -- Bool uses `getU8`/`setU8` in structs because WinRT Boolean is 1 byte in struct layout -- Bool uses `boolValue()` for method params, creating `WinRTValue::Bool` (correct ABI width) -- I64/U64 return uses `.toI64()` (not `.toNumber()` which truncates to i32) -- F32/F64 return uses `.toF64()` (not `.toNumber()` which truncates to i32) -- Small integer params (I8, U8, I16, U16) wrapped as `i32()` — the runtime truncates at ABI call time - -## String & GUID - -| WinRT Type | TS Type | wrap_arg | convert_return | Struct getter | Struct setter | -|---|---|---|---|---|---| -| String (HSTRING) | `string` | `hstring(x)` | `.toString()` | `getHstring(i)` | `setHstring(i, x)` | -| Guid | `string` | `guid(WinGuid.parse(x))` | `.toString()` | `getGuid(i).toString()` | `setGuid(i, WinGuid.parse(x))` | - -### Notes -- HSTRING in struct fields is non-blittable. `getHstring`/`setHstring` use `get_field_struct`/`set_field_struct` internally with proper refcount management (duplicate on read, release old + duplicate new on write) -- GUID is 16 bytes, blittable. `getGuid`/`setGuid` use `get_field::()`/`set_field()` directly - -## Enum - -| WinRT Type | TS Type | wrap_arg | convert_return | Struct getter | Struct setter | -|---|---|---|---|---|---| -| Enum | `EnumName` | `i32(x)` | `.toNumber()` | `getI32(i)` | `setI32(i, x)` | - -Generated as TypeScript `enum` with numeric values. ABI is always Int32. - -## Struct (Value Type) - -| WinRT Type | TS Type | wrap_arg | convert_return | +| WinRT type | JavaScript / TypeScript | Python | ABI notes | |---|---|---|---| -| Struct | `StructName` (interface) | `_packXxx(x).toValue()` | `_unpackXxx(expr)` | -| HResult | `number` | `i32(x)` | `.toNumber()` | - -### Implementation - -For each non-HResult struct used in method signatures, the codegen generates: - -```typescript -// 1. TypeScript interface with camelCase field names -interface Point { x: number; y: number; } - -// 2. Unpack: DynWinRtValue -> plain JS object -function _unpackPoint(v: DynWinRtValue): Point { - const s = v.asStruct(); - return { x: s.getF32(0), y: s.getF32(1) }; -} - -// 3. Type constant for struct creation -const _Point_Type = DynWinRtType.registerStruct('Windows.Foundation.Point', [DynWinRtType.f32(), DynWinRtType.f32()]); - -// 4. Pack: plain JS object -> DynWinRtStruct -function _packPoint(v: Point): DynWinRtStruct { - const s = DynWinRtStruct.create(_Point_Type); - s.setF32(0, v.x); - s.setF32(1, v.y); - return s; -} -``` - -### Supported struct field types -- All primitives (Bool, I8..U64, F32, F64) via typed getters/setters -- Enum via `getI32`/`setI32` -- String via `getHstring`/`setHstring` (non-blittable, refcounted) -- Guid via `getGuid`/`setGuid` (16-byte blittable) -- Nested struct via `getStruct`/`setStruct` + recursive `_unpack`/`_pack` -- IReference\ (COM pointer) via `getObject`/`setObject` (rare, fallback to DynWinRtValue) - -### Dependency ordering -Struct helpers are generated in post-order (inner structs before outer). E.g., if `ManipulationDelta` contains a `Point` field, `_unpackPoint` is generated before `_unpackManipulationDelta`. - -### DynWinRtStruct import -The `DynWinRtStruct` import is only added to files that actually use structs, to avoid unused import warnings. - -## Array - -### As method return (WinRT -> JS) - -The codegen auto-converts array returns to native JS arrays: - -| Element Type | TS Return Type | Conversion | +| `Boolean` | `boolean` | `bool` | One-byte WinRT boolean storage | +| `Int8`–`UInt32`, `Char16` | `number` | `int` | Inputs are range checked at the language boundary | +| `Int64`, `UInt64` | `bigint` | `int` | JavaScript accepts safe integers where documented, but generated APIs preserve the full range with `bigint` | +| `Single`, `Double` | `number` | `float` | `Single` is narrowed to the native `f32` ABI | +| `String` / `HSTRING` | `string` | `str` | Runtime duplicates and releases owned HSTRING values | +| `Guid` | `string` | `uuid.UUID` | Native 16-byte GUID layout | +| `HRESULT` value | `number` | `int` | Method failures become language exceptions; semantic HRESULT returns remain values | +| Enum | frozen numeric object + declaration type | `enum.IntEnum` | Unknown Python enum values remain integers | +| Flags enum | frozen numeric object + declaration type | `enum.IntFlag` | Native storage follows metadata, normally `Int32` | +| `DateTime` | generated struct value | `datetime.datetime` | Python values are normalized to UTC WinRT ticks | +| `TimeSpan` | generated struct value | `datetime.timedelta` | Python converts to and from 100-nanosecond ticks | + +## Reference and nullable types + +| WinRT type | JavaScript / TypeScript | Python | |---|---|---| -| I8 | `number[]` | `.asArray().toI8Vec()` | -| U8 | `number[]` | `.asArray().toU8Vec()` | -| I16 | `number[]` | `.asArray().toI16Vec()` | -| U16 / Char16 | `number[]` | `.asArray().toU16Vec()` | -| I32 / Enum | `number[]` | `.asArray().toI32Vec()` | -| U32 | `number[]` | `.asArray().toU32Vec()` | -| I64 | `number[]` | `.asArray().toI64Vec()` | -| U64 | `number[]` | `.asArray().toU64Vec()` | -| F32 | `number[]` | `.asArray().toF32Vec()` | -| F64 | `number[]` | `.asArray().toF64Vec()` | -| Boolean | `boolean[]` | `.asArray().toValues().map(v => v.toBool())` | -| String | `string[]` | `.asArray().toStringVec()` | -| Guid | `string[]` | `.asArray().toValues().map(v => v.toString())` | -| Struct | `StructName[]` | `.asArray().toValues().map(v => _unpackXxx(v))` | -| RuntimeClass | `ClassName[]` | `.asArray().toValues().map(v => new ClassName(v))` | -| Object | `DynWinRtValue[]` | `.asArray().toValues()` | +| Runtime class | generated wrapper | generated wrapper | +| Interface | generated interface wrapper | generated structural interface wrapper | +| `Object` / `IInspectable` | `DynWinRtValue` | `DynWinRTValue` | +| `IReference` output | `T \| null` | `T \| None` | +| `IReference` input | native value, `null`, or generated compatibility wrapper | native value, `None`, or generated compatibility wrapper | +| Delegate input | generated delegate/callback surface | normal Python callable | -### As method parameter (JS -> WinRT) +Returned runtime classes and interfaces own their native reference. Generated +wrappers provide explicit projection and interface-conversion helpers for +metadata that exposes only `Object`/`IInspectable`. -Input arrays use `DynWinRtArray` type. Users construct arrays via factory methods: +## Structs -```typescript -DynWinRtArray.fromI32Values([1, 2, 3]) -DynWinRtArray.fromStringValues(["a", "b"]) -``` +Struct layout comes from metadata and includes native size, alignment, nested +fields, enums, fixed arrays, HSTRING fields, GUIDs, and interface-valued fields. +The core runtime clones and drops non-blittable fields with the required +reference counting. -Available `fromXxxValues`: i8, u8, i16, u16, i32, u32, f32, f64, i64, u64, string. +JavaScript projects structs as typed plain objects and generates internal +pack/unpack helpers. Python emits one canonical generated value class per struct +and uses native Python values for GUID, `DateTime`, `TimeSpan`, and nullable +fields. -### Array out parameters +Unknown or incomplete layouts fail during generation instead of being treated +as an opaque object. -WinRT ReceiveArray/FillArray patterns (array as `[out]` parameter, no retval) are handled identically — the codegen detects the array out param, determines the element type, and applies the same conversion. +## Arrays and collections -## Reference Types +WinRT pass, receive, and fill arrays are modeled separately so capacity, +actual-length, allocation, and element cleanup remain correct. -| WinRT Type | TS Type | wrap_arg | convert_return | -|---|---|---|---| -| Object (IInspectable) | `DynWinRtValue` | `(x as any)._obj ?? x` | raw (no conversion) | -| RuntimeClass | `ClassName` | `(x as any)._obj ?? x` | `new ClassName(expr)` | -| Interface | `InterfaceName` | `(x as any)._obj ?? x` | `new InterfaceName(expr)` | -| Delegate | `DynWinRtValue` | `(x as any)._obj ?? x` | raw (no conversion) | -| Parameterized | `ConcreteName` | `(x as any)._obj ?? x` | `new ConcreteName(expr)` | +- JavaScript generated APIs accept and return typed arrays such as `number[]`, + `bigint[]`, `string[]`, and generated wrapper arrays. +- Python generated APIs accept normal sequences. Byte arrays accept `bytes` and + `bytearray`; outputs use native Python values where possible. +- Runtime-class, interface, HSTRING, struct, enum, GUID, and primitive elements + preserve their native ownership and ABI representation. -### Notes -- `(x as any)._obj ?? x` extracts the underlying `DynWinRtValue` from wrapper classes, or passes raw if already a `DynWinRtValue` -- RuntimeClass/Interface returns are wrapped in generated constructor only when the type is in `known_types` (has a generated .ts file) -- Unknown reference types fall through to `DynWinRtValue` +Parameterized collections are generated as concrete interfaces: -## Async +- `IIterable` and `IIterator`; +- `IVector` and `IVectorView`; +- `IObservableVector`; +- `IMap`, `IMapView`, and `IKeyValuePair`. -| WinRT Type | TS Return Type | Conversion | -|---|---|---| -| IAsyncAction | `Promise` | `.toPromise()` | -| IAsyncOperation\ | `Promise` | `(await expr.toPromise())` then convert inner T | -| IAsyncActionWithProgress\ | `Promise` | `.toPromise()` | -| IAsyncOperationWithProgress\ | `Promise` | `(await expr.toPromise())` then convert inner T | +JavaScript exposes the projected WinRT methods and convenience helpers. Python +implements the matching `collections.abc` sequence, mutable-sequence, mapping, +mutable-mapping, iterable, and iterator protocols. -The async unwrap is recursive: `convert_return` first unwraps the Promise, then applies the inner type's conversion. E.g., `IAsyncOperation` generates `(await expr.toPromise()).toString()`. +## Async operations -## Events (Delegates) - -| Pattern | TS Signature | Implementation | -|---|---|---| -| `add_EventName` | `onEventName(callback)` | `DynWinRtDelegate.create(IID, paramTypes, callback)` | -| `remove_EventName` | `offEventName(token)` | Pass token back to remove method | - -Delegate IIDs and parameter types are generated as exports (`IID_DelegateName`, `DelegateName_PARAM_TYPES`) for use with `DynWinRtDelegate.create()`. - -## DynWinRtStruct napi API - -Complete field access API exposed to JavaScript: - -| Method | Reads/Writes | Byte size | -|---|---|---| -| `getI8` / `setI8` | i8 | 1 | -| `getU8` / `setU8` | u8 | 1 | -| `getI16` / `setI16` | i16 | 2 | -| `getU16` / `setU16` | u16 | 2 | -| `getI32` / `setI32` | i32 | 4 | -| `getU32` / `setU32` | u32 | 4 | -| `getF32` / `setF32` | f32 | 4 | -| `getF64` / `setF64` | f64 | 8 | -| `getI64` / `setI64` | i64 | 8 | -| `getU64` / `setU64` | u64 | 8 | -| `getHstring` / `setHstring` | HSTRING | ptr (non-blittable) | -| `getGuid` / `setGuid` | GUID | 16 | -| `getStruct` / `setStruct` | nested struct | variable (non-blittable safe) | -| `getObject` / `setObject` | COM pointer | ptr (non-blittable) | -| `create(type)` | — | Allocates zero-initialized struct | -| `toValue()` | — | Wraps as DynWinRtValue for method calls | - -### Memory safety -- `getHstring`/`getStruct`/`getObject` use `get_field_struct()` which clones non-blittable fields (AddRef/WindowsDuplicateString) -- `setHstring`/`setStruct`/`setObject` use `set_field_struct()` which releases old field values before writing + clones new values -- `ValueTypeData` implements `Clone` (deep copy with refcount increment) and `Drop` (release all non-blittable fields) - -## DynWinRtArray napi API - -### Read (WinRT -> JS) - -| Method | Element type | Implementation | -|---|---|---| -| `toI8Vec()` | i8 → i32 | `as_typed_slice::` + widen | -| `toU8Vec()` | u8 | `as_typed_slice::` (zero-copy) | -| `toI16Vec()` | i16 → i32 | `as_typed_slice::` + widen | -| `toU16Vec()` | u16 → u32 | `as_typed_slice::` + widen | -| `toI32Vec()` | i32 | `as_typed_slice::` (zero-copy) | -| `toU32Vec()` | u32 | `as_typed_slice::` (zero-copy) | -| `toF32Vec()` | f32 | `as_typed_slice::` (zero-copy) | -| `toF64Vec()` | f64 | `as_typed_slice::` (zero-copy) | -| `toI64Vec()` | i64 | `as_typed_slice::` (zero-copy) | -| `toU64Vec()` | u64 → i64 | `as_typed_slice::` + cast | -| `toStringVec()` | HSTRING → String | Per-element `get()` + convert | -| `toValues()` | any → DynWinRtValue | Per-element `get()` (generic) | - -### Write (JS -> WinRT) - -| Method | JS input | WinRT value | +| WinRT type | JavaScript / TypeScript | Python | |---|---|---| -| `fromI8Values(i32[])` | number[] | WinRTValue::I8 | -| `fromU8Values(u8[])` | number[] | WinRTValue::U8 | -| `fromI16Values(i32[])` | number[] | WinRTValue::I16 | -| `fromU16Values(u32[])` | number[] | WinRTValue::U16 | -| `fromI32Values(i32[])` | number[] | WinRTValue::I32 | -| `fromU32Values(u32[])` | number[] | WinRTValue::U32 | -| `fromF32Values(f64[])` | number[] | WinRTValue::F32 | -| `fromF64Values(f64[])` | number[] | WinRTValue::F64 | -| `fromI64Values(i64[])` | number[] | WinRTValue::I64 | -| `fromU64Values(i64[])` | number[] | WinRTValue::U64 | -| `fromStringValues(String[])` | string[] | WinRTValue::HString | - -## Known Limitations - -1. **IReference\ as struct field** — napi has `getObject`/`setObject`, codegen has fallback, but untested in practice (only `Windows.Web.Http.HttpProgress` uses this pattern in Windows.winmd) -2. **U64 precision** — JS number (f64) can only represent integers exactly up to 2^53. U64 values beyond that range lose precision. This is a JS language limitation. -3. **Guid array** — Uses `.toValues().map(v => v.toString())` (per-element), no native `toGuidVec()`. Low priority since Guid arrays are rare. -4. **Bool array** — Uses `.toValues().map(v => v.toBool())` (per-element), no native `toBoolVec()`. +| `IAsyncAction` | `Promise` | `WinRTAsync[None]` | +| `IAsyncOperation` | `Promise` | `WinRTAsync[T]` | +| `IAsyncActionWithProgress

` | Promise + progress callback | `WinRTAsyncWithProgress[None, P]` | +| `IAsyncOperationWithProgress` | Promise + progress callback | `WinRTAsyncWithProgress[T, P]` | + +Cancellation calls `IAsyncInfo.Cancel`. Python awaitables integrate with +`asyncio` and also expose an explicit blocking `wait()` API for non-async +hosts. Blocking waits are rejected on an STA or from a running event loop when +they could deadlock. + +## Delegates and events + +Generated event methods retain the WinRT token model. JavaScript and Python +bindings marshal callbacks through their host runtimes and report callback +failures as failing HRESULTs instead of unconditional success. + +The shared dynamic WinRT delegate currently supports up to two ABI parameters. +This covers common handlers such as `TypedEventHandler`, +`EventHandler`, and async completion/progress handlers. Delegates with more +than two ABI parameters remain unsupported. + +## Activation, composition, and WinUI + +Public `ActivatableAttribute` and `ComposableAttribute` metadata becomes normal +language constructors. Protected-only composition and system-returned classes +remain non-constructible but can still be wrapped when returned by Windows. + +Both generators include specialized WinUI `Application + Window` support, +metadata-provider/resource helpers, composable controls, DispatcherQueue +integration, and projected lifetime management. The application must still +provide package identity or Windows App SDK bootstrap, the correct STA thread, +and lifecycle ownership. + +## Validation and remaining limits + +Coverage is enforced through: + +- core ABI and ownership tests; +- JavaScript and Python binding tests; +- generated JavaScript, declaration, Python, and stub snapshots; +- TypeScript and mypy checks; and +- x64/ARM64 end-to-end tests against real Windows APIs. + +Current limits that affect type coverage: + +1. Dynamic WinRT delegates accept at most two ABI parameters. +2. JavaScript GUID and Boolean arrays use per-element conversion rather than a + dedicated bulk fast path. +3. Python does not yet expose a zero-copy buffer protocol for WinRT buffers. +4. Classic COM, native Win32 pointers, Automation variants, SAFEARRAY, and + ownership-specific outputs use the separate fail-closed COM model and + currently generate only JavaScript/TypeScript. diff --git a/tools/dynwinrt-codegen/npm/README.md b/tools/dynwinrt-codegen/npm/README.md index d4e74b3a..dbb206de 100644 --- a/tools/dynwinrt-codegen/npm/README.md +++ b/tools/dynwinrt-codegen/npm/README.md @@ -1,6 +1,6 @@ # @microsoft/dynwinrt-codegen -**Generate typed JavaScript + TypeScript bindings for any Windows Runtime (WinRT) API from `.winmd` metadata.** +**Generate typed JavaScript + TypeScript bindings for Windows Runtime (WinRT) APIs from `.winmd` metadata.** Pair this with the [`@microsoft/dynwinrt`](https://www.npmjs.com/package/@microsoft/dynwinrt) runtime to call modern Windows APIs (WinAppSDK, Windows AI, notifications, storage, networking, …) **directly from JavaScript / TypeScript** — full IntelliSense, no native build step, no C# projection, no per-Windows-version recompile. @@ -21,7 +21,11 @@ const model = await LanguageModel.createAsync(); You get IntelliSense in your IDE, type errors at `tsc` time, and the underlying COM call dispatched dynamically at runtime — no MSBuild involved. -The trade-off: `dynwinrt-codegen` is designed for **data-style WinRT APIs** (AI, storage, notifications, networking, globalization, …) and skips XAML / WinUI namespaces, which need composable-class aggregation patterns the codegen doesn't implement. For everything else, this is the easiest path from JavaScript to native Windows. +`dynwinrt-codegen` primarily targets **data-style WinRT APIs** (AI, storage, +notifications, networking, globalization, …). It also generates WinUI +`Application + Window` helpers and public composable classes; the application +must provide an STA UI thread, Windows App SDK bootstrap or package identity, +and lifecycle management. ## CLI usage @@ -68,7 +72,8 @@ For each WinRT class, the codegen emits: - **An interface registration** (`DynWinRtType.registerInterface()`) wired to the COM vtable - **A JavaScript-backed `IElementFactory.create()` helper** for WinUI ItemsRepeater realization and recycling -- **`IAsyncOperation` awaitables** with `.progress(cb)` for streaming results +- **Promise-based async operations**, with `.progress(cb)` on operations that + expose WinRT progress - **Generic collections** (`IVector`, `IMap`, `IIterable`) - **Creatable observable vectors** that expose both `IObservableVector` events and `IVector` mutation helpers @@ -77,6 +82,12 @@ For each WinRT class, the codegen emits: - **Delegate types** (IID + parameter signatures) for event handlers - **An `index.js` + `index.d.ts`** re-exporting every emitted symbol from one place +Classic COM generation from `Windows.Win32.winmd` is available as a preview. +Only interfaces with complete validated ABI, layout, ownership, and cleanup +contracts are emitted under the generated `com/` subpackage; unsupported +interfaces fail closed. See the +[Classic COM usage guide](https://github.com/microsoft/dynwinrt/blob/main/docs/guides/windows/classic-com-usage.md). + ## Platform - **Windows only** (x64 / arm64) — the binary is built per architecture and selected automatically by the npm install diff --git a/tools/dynwinrt-codegen/src/main.rs b/tools/dynwinrt-codegen/src/main.rs index 07bef6ff..e8dab056 100644 --- a/tools/dynwinrt-codegen/src/main.rs +++ b/tools/dynwinrt-codegen/src/main.rs @@ -81,9 +81,9 @@ enum Commands { /// Generate bindings from .winmd files #[command( long_about = "Parse .winmd metadata and generate typed binding files.\n\n\ - By default (`--lang js`) the tool emits plain ESM JavaScript (`.js`) plus\n\ - matching ambient TypeScript declarations (`.d.ts`) — no TypeScript compiler\n\ - or SWC step is involved.\n\n\ + By default (`--lang js`) the tool emits CommonJS JavaScript (`.js`), ESM\n\ + facades (`.mjs`), and matching ambient TypeScript declarations (`.d.ts`) —\n\ + no TypeScript compiler or SWC step is involved.\n\n\ The tool automatically:\n\ - Detects Windows.winmd from the Windows SDK install path\n\ - Discovers sibling .winmd files in the same directory as --winmd\n\