Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,24 @@ jobs:
- uses: dtolnay/rust-toolchain@stable
with:
targets: i686-pc-windows-msvc
- uses: actions/setup-node@v4
with:
node-version: 24
- name: Install declaration test compiler
shell: pwsh
run: |
npm install --prefix target/tsc --no-save --ignore-scripts --no-package-lock typescript@5.9.3
$tsc = (Resolve-Path target/tsc/node_modules/typescript/bin/tsc).Path
$windowsWinmd = Get-ChildItem 'C:\Program Files (x86)\Windows Kits\10\UnionMetadata' `
-Filter Windows.winmd -File -Recurse |
Sort-Object FullName -Descending |
Select-Object -First 1
if (-not $windowsWinmd) {
throw 'Windows SDK metadata is required for declaration tests'
}
"DYNWINRT_TSC=$tsc" >> $env:GITHUB_ENV
"DYNWINRT_WINDOWS_WINMD=$($windowsWinmd.FullName)" >> $env:GITHUB_ENV
"DYNWINRT_REQUIRE_TSC=1" >> $env:GITHUB_ENV
- uses: NuGet/setup-nuget@v2
- name: Install Win32 metadata
shell: pwsh
Expand Down
31 changes: 28 additions & 3 deletions bindings/js/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,29 @@ console.log(uri.host); // "example.com"
console.log(uri.port); // 443
```

### Generated module layout

Generated WinRT implementations use canonical namespace paths. Prefer the root
barrel for concise imports:

```js
const { Uri, Button } = require('./generated');
```

Use the canonical path when a deep import is needed:

```js
const { Uri } = require('./generated/windows/foundation/Uri.js');
const { Button } = require(
'./generated/microsoft/ui/xaml/controls/Button.js'
);
```

Legacy flat paths such as `./generated/Uri.js` are not generated. When metadata
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:

Expand Down Expand Up @@ -85,9 +108,11 @@ runtime class. It accepts either a raw projected value or an existing wrapper,
borrows the input, and creates a separately releasable projection:

```js
import { projectAs } from "./generated/lifetime.js";
import { XamlReader } from "./generated/XamlReader.js";
import { StackPanel } from "./generated/StackPanel.js";
import {
projectAs,
StackPanel,
XamlReader,
} from "./generated/index.mjs";

const raw = XamlReader.load(xaml);
if (raw === null) throw new Error("XamlReader returned no value");
Expand Down
2 changes: 1 addition & 1 deletion samples/js/electron-share-ui/src/main/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { app, BrowserWindow, ipcMain } from 'electron'
import { is } from '@electron-toolkit/utils'
import { initializeCom } from '@microsoft/dynwinrt/com'
import { roInitialize } from '@microsoft/dynwinrt'
import { DataTransferManager } from '../../generated/DataTransferManager.js'
import { DataTransferManager } from '../../generated/windows/application-model/data-transfer/DataTransferManager.js'
import { projectAs, releaseProjected } from '../../generated/lifetime.js'
import { IDataTransferManagerInterop } from '../../generated/com/IDataTransferManagerInterop.js'

Expand Down
18 changes: 4 additions & 14 deletions samples/js/electron-smtc/media-controls.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,25 +4,15 @@
const path = require("node:path");
const {
GlobalSystemMediaTransportControlsSessionManager,
} = require("./generated/GlobalSystemMediaTransportControlsSessionManager.js");
const {
MediaPlaybackAutoRepeatMode,
} = require("./generated/MediaPlaybackAutoRepeatMode.js");
const { MediaPlaybackStatus } = require("./generated/MediaPlaybackStatus.js");
const { MediaPlaybackType } = require("./generated/MediaPlaybackType.js");
const {
MediaPlaybackStatus,
MediaPlaybackType,
RandomAccessStreamReference,
} = require("./generated/RandomAccessStreamReference.js");
const { StorageFile } = require("./generated/StorageFile.js");
const {
StorageFile,
SystemMediaTransportControls,
} = require("./generated/SystemMediaTransportControls.js");
const {
SystemMediaTransportControlsButton,
} = require("./generated/SystemMediaTransportControlsButton.js");
const {
SystemMediaTransportControlsTimelineProperties,
} = require("./generated/SystemMediaTransportControlsTimelineProperties.js");
} = require("./generated/index.js");
const {
ISystemMediaTransportControlsInterop,
} = require("./generated/com/ISystemMediaTransportControlsInterop.js");
Expand Down
4 changes: 2 additions & 2 deletions samples/js/windows-hello/check.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@
// Licensed under the MIT License.

const { roInitialize } = require('@microsoft/dynwinrt')
const { UserConsentVerifier } = require('./generated/UserConsentVerifier.js')
const {
UserConsentVerifier,
UserConsentVerifierAvailability,
} = require('./generated/UserConsentVerifierAvailability.js')
} = require('./generated/index.js')

function enumName(values, value) {
return Object.entries(values).find(([, candidate]) => candidate === value)?.[0] ?? `Unknown (${value})`
Expand Down
6 changes: 2 additions & 4 deletions samples/js/windows-hello/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,11 @@ const {
DynWinRtValue,
} = require('@microsoft/dynwinrt')
const { DynCom } = require('@microsoft/dynwinrt/com/unsafe')
const { UserConsentVerifier } = require('./generated/UserConsentVerifier.js')
const {
UserConsentVerifier,
UserConsentVerifierAvailability,
} = require('./generated/UserConsentVerifierAvailability.js')
const {
UserConsentVerificationResult,
} = require('./generated/UserConsentVerificationResult.js')
} = require('./generated/index.js')
const {
IUserConsentVerifierInterop,
} = require('./generated/com/IUserConsentVerifierInterop.js')
Expand Down
4 changes: 2 additions & 2 deletions tests/e2e/runners/com/smtc.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,9 @@ import { acquireHwndBigInt } from './hwnd.mjs';

// Full WinRT natural projection generated by the unified E2E orchestrator.
const { SystemMediaTransportControls: SmtcProjected } =
await import('../../e2e_generated/com/smtc/SystemMediaTransportControls.js');
await import('../../e2e_generated/com/smtc/windows/media/SystemMediaTransportControls.js');
const { MediaPlaybackStatus } =
await import('../../e2e_generated/com/smtc/MediaPlaybackStatus.js');
await import('../../e2e_generated/com/smtc/windows/media/MediaPlaybackStatus.js');

function fail(msg) {
console.error(`[e2e] FAIL: ${msg}`);
Expand Down
10 changes: 6 additions & 4 deletions tests/e2e/runners/ts_issue_regression_child.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// Licensed under the MIT License.

import * as path from 'node:path'
import { createRequire } from 'node:module'
import { pathToFileURL } from 'node:url'

const [name, generatedDir, runtimePath] = process.argv.slice(2)
Expand All @@ -10,12 +11,13 @@ if (!name || !generatedDir || !runtimePath) {
throw new Error('Usage: ts_issue_regression_child.mjs <name> <generated> <runtime>')
}

const require = createRequire(import.meta.url)
const generatedRoot = require(path.resolve(generatedDir, 'index.js'))

const importGenerated = async (className) => {
const moduleUrl = pathToFileURL(path.resolve(generatedDir, `${className}.js`)).href
const module = await import(moduleUrl)
const cls = module[className]
const cls = generatedRoot[className]
if (!cls) {
throw new Error(`${className} was not exported by ${moduleUrl}`)
throw new Error(`${className} was not exported by the generated root`)
}
return cls
}
Expand Down
86 changes: 37 additions & 49 deletions tests/e2e/runners/ts_runner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
import { strict as assert } from "node:assert";
import { spawn } from "node:child_process";
import * as fs from "node:fs";
import { createRequire } from "node:module";
import * as os from "node:os";
import * as path from "node:path";
import { fileURLToPath } from "node:url";
Expand Down Expand Up @@ -71,6 +72,18 @@ interface SpecResult {
error: string | null;
}

const require = createRequire(import.meta.url);
const generatedRoots = new Map<string, any>();

function generatedRoot(generatedDir: string): any {
let root = generatedRoots.get(generatedDir);
if (!root) {
root = require(path.resolve(generatedDir, "index.js"));
generatedRoots.set(generatedDir, root);
}
return root;
}

function toSnakeCase(name: string): string {
return name
.replace(/([A-Z])/g, "_$1")
Expand Down Expand Up @@ -105,9 +118,8 @@ async function runSpec(
};

try {
// Import the generated module
const modulePath = path.resolve(generatedDir, `${spec.class}.js`);
const mod = await import(`file://${modulePath.replace(/\\/g, "/")}`);
const modulePath = path.resolve(generatedDir, "index.js");
const mod = generatedRoot(generatedDir);
const cls = mod[spec.class];
if (!cls) throw new Error(`Class ${spec.class} not found in ${modulePath}`);

Expand Down Expand Up @@ -178,17 +190,10 @@ async function importClass(
generatedDir: string,
className: string,
): Promise<any> {
const candidates = [
path.resolve(generatedDir, `${className}.js`),
path.resolve(generatedDir, `${toPascalCase(className)}.js`),
];
for (const p of candidates) {
if (fs.existsSync(p)) {
const mod = await import(`file://${p.replace(/\\/g, "/")}`);
if (mod[className]) return mod[className];
}
}
throw new Error(`Class ${className} not found in: ${candidates.join(", ")}`);
const root = generatedRoot(generatedDir);
const cls = root[className] ?? root[toPascalCase(className)];
if (cls) return cls;
throw new Error(`Class ${className} not found in generated root`);
}

async function runIssueRegression(
Expand Down Expand Up @@ -442,13 +447,9 @@ async function runCheck(
return cr;
}

const propertyValueMod = await import(
`file://${path.resolve(generatedDir, "PropertyValue.js").replace(/\\/g, "/")}`
);
const propertyValueMod = generatedRoot(generatedDir);
const referenceModule = (check as any).reference_class;
const referenceMod = await import(
`file://${path.resolve(generatedDir, `${referenceModule}.js`).replace(/\\/g, "/")}`
);
const referenceMod = generatedRoot(generatedDir);
const factory =
propertyValueMod.PropertyValue[
(check as any).factory.replace(/_([a-z])/g, (_: string, c: string) =>
Expand Down Expand Up @@ -654,8 +655,7 @@ async function runCheck(
cr.pass = true;
}
} else if (kind === "nested_struct_runtime") {
const modulePath = path.resolve(generatedDir, `${clsName}.js`);
const mod = await import(`file://${modulePath.replace(/\\/g, "/")}`);
const mod = generatedRoot(generatedDir);
const DirectXPixelFormat = await importClass(
generatedDir,
"DirectXPixelFormat",
Expand Down Expand Up @@ -720,18 +720,7 @@ async function runCheck(
}
} else if (kind === "struct_roundtrip") {
const structClass = check.struct_class as string;
const structModule = check.struct_module as string;
// In TS, structs are interfaces + packFn. Find the module file.
const candidates = [
path.resolve(generatedDir, `${toPascalCase(structModule)}.js`),
path.resolve(generatedDir, `${structModule}.js`),
];
let modPath = candidates.find((p) => fs.existsSync(p));
if (!modPath)
throw new Error(
`Struct module not found: tried ${candidates.join(", ")}`,
);
const structMod = await import(`file://${modPath.replace(/\\/g, "/")}`);
const structMod = generatedRoot(generatedDir);

// TS structs are plain objects (interfaces), create one directly
const structArgs = check.struct_args as Record<string, any>;
Expand Down Expand Up @@ -795,12 +784,8 @@ async function runCheck(
const stream =
typeof cls.create === "function" ? cls.create() : cls.createDefault();

const writerMod = await import(
`file://${path.resolve(generatedDir, "DataWriter.js").replace(/\\/g, "/")}`
);
const readerMod = await import(
`file://${path.resolve(generatedDir, "DataReader.js").replace(/\\/g, "/")}`
);
const writerMod = generatedRoot(generatedDir);
const readerMod = generatedRoot(generatedDir);
const DataWriter = writerMod.DataWriter;
const DataReader = readerMod.DataReader;

Expand Down Expand Up @@ -891,10 +876,7 @@ async function runCheck(
let chainOk = true;
for (const step of (check as any).steps) {
const stepClsName = step.class;
const stepModPath = path.resolve(generatedDir, `${stepClsName}.js`);
const stepMod = await import(
`file://${stepModPath.replace(/\\/g, "/")}`
);
const stepMod = generatedRoot(generatedDir);
const stepCls = stepMod[stepClsName];
const stepMethodName = toCamelCase(step.method);
const stepMethod =
Expand Down Expand Up @@ -971,11 +953,17 @@ async function main() {

// Fix imports in generated files (both ESM `import ... from` and CJS `require`)
const absRuntime = path.resolve(runtimePath).replace(/\\/g, "/");
const tsFiles = fs
.readdirSync(generatedDir)
.filter((f) => f.endsWith(".js") || f.endsWith(".mjs"));
for (const f of tsFiles) {
const filePath = path.join(generatedDir, f);
const generatedModules: string[] = [];
const collectGeneratedModules = (directory: string): void => {
for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
const entryPath = path.join(directory, entry.name);
if (entry.isDirectory()) collectGeneratedModules(entryPath);
else if (entry.name.endsWith(".js") || entry.name.endsWith(".mjs"))
generatedModules.push(entryPath);
}
};
collectGeneratedModules(generatedDir);
for (const filePath of generatedModules) {
let content = fs.readFileSync(filePath, "utf8");
content = content.replace(
/from '@microsoft\/dynwinrt'/g,
Expand Down
4 changes: 2 additions & 2 deletions tools/dynwinrt-codegen/E2E_TEST.md
Original file line number Diff line number Diff line change
Expand Up @@ -78,8 +78,8 @@ Create `test_picker.ts` in the test project (TypeScript here — the same import

```typescript
import { initWinappsdk, roInitialize, DynWinRtValue } from '@microsoft/dynwinrt'
import { FileOpenPicker } from './generated/FileOpenPicker.js'
import { PickerViewMode } from './generated/PickerViewMode.js'
import { FileOpenPicker } from './generated/windows/storage/pickers/FileOpenPicker.js'
import { PickerViewMode } from './generated/windows/storage/pickers/PickerViewMode.js'

async function main() {
initWinappsdk(1, 8)
Expand Down
7 changes: 6 additions & 1 deletion tools/dynwinrt-codegen/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,11 +37,16 @@ npx dynwinrt-codegen generate [OPTIONS]
| `--class-name` | No | Class name(s) to generate, comma-separated (requires `--namespace`). E.g. `StorageFile` or `StorageFile,StorageFolder` |
| `--ref` | No | Additional `.winmd` files for type resolution only (no code generated). Paths separated by `;` |
| `--lang` | No | Target language: `js` (default, emits `.js` + `.d.ts`) or `py` (emits `.py`, optionally `.pyi`) |
| `--output` | No | Output directory (default: `./generated`) |
| `--output` | No | Codegen-owned output directory (default: `./generated`). Existing contents may be replaced or removed; do not store handwritten files here. |
| `--dry-run` | No | Validate metadata and resolve dependencies without writing files |

With `--lang js` (default), the tool emits plain ESM JavaScript (`.js`) plus matching ambient TypeScript declarations (`.d.ts`). No TypeScript compiler is needed — the output works for both JS and TS consumers. JSDoc comments are preserved so VS Code IntelliSense shows API descriptions.

Repeated commands may append bindings to the same output directory when they
use the same restored metadata version. After changing WinMD files, SDK
versions, or reference inputs, delete the codegen-owned output directory and
run all generation commands again.

> **Note:** Legacy flags `--lang ts`, `--lang cjs`, `--source-map`, `--declaration`, and `--no-declaration` are accepted by the npm CLI wrapper for backwards compatibility but are silently mapped to `--lang js` behavior.

### Examples
Expand Down
6 changes: 4 additions & 2 deletions tools/dynwinrt-codegen/src/codegen/winrt/javascript/ir.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,8 +65,10 @@ pub enum ProjectedMember {
Symbol(ProjectedSymbol),
/// `.as<T>()` generic cast
AsCast,
/// `.close()` from IClosable
Close,
/// `.close()` from the projected IClosable interface.
Close {
interface_name: String,
},
}

#[derive(Clone)]
Expand Down
Loading
Loading