diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index e43d0a06..76fcc044 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -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 diff --git a/bindings/js/README.md b/bindings/js/README.md index a7daaa6f..0ad1b018 100644 --- a/bindings/js/README.md +++ b/bindings/js/README.md @@ -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: @@ -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"); diff --git a/samples/js/electron-share-ui/src/main/index.ts b/samples/js/electron-share-ui/src/main/index.ts index 9a53b6af..60125d61 100644 --- a/samples/js/electron-share-ui/src/main/index.ts +++ b/samples/js/electron-share-ui/src/main/index.ts @@ -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' diff --git a/samples/js/electron-smtc/media-controls.js b/samples/js/electron-smtc/media-controls.js index 7e51d502..2e433554 100644 --- a/samples/js/electron-smtc/media-controls.js +++ b/samples/js/electron-smtc/media-controls.js @@ -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"); diff --git a/samples/js/windows-hello/check.js b/samples/js/windows-hello/check.js index eca5ff03..82f13278 100644 --- a/samples/js/windows-hello/check.js +++ b/samples/js/windows-hello/check.js @@ -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})` diff --git a/samples/js/windows-hello/main.js b/samples/js/windows-hello/main.js index 4ce53f53..0b9414d6 100644 --- a/samples/js/windows-hello/main.js +++ b/samples/js/windows-hello/main.js @@ -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') diff --git a/tests/e2e/runners/com/smtc.mjs b/tests/e2e/runners/com/smtc.mjs index a3221fb7..2155d44d 100644 --- a/tests/e2e/runners/com/smtc.mjs +++ b/tests/e2e/runners/com/smtc.mjs @@ -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}`); diff --git a/tests/e2e/runners/ts_issue_regression_child.mjs b/tests/e2e/runners/ts_issue_regression_child.mjs index 31542c22..7bae9aba 100644 --- a/tests/e2e/runners/ts_issue_regression_child.mjs +++ b/tests/e2e/runners/ts_issue_regression_child.mjs @@ -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) @@ -10,12 +11,13 @@ if (!name || !generatedDir || !runtimePath) { throw new Error('Usage: ts_issue_regression_child.mjs ') } +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 } diff --git a/tests/e2e/runners/ts_runner.ts b/tests/e2e/runners/ts_runner.ts index 2bdaa0c8..ee484c86 100644 --- a/tests/e2e/runners/ts_runner.ts +++ b/tests/e2e/runners/ts_runner.ts @@ -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"; @@ -71,6 +72,18 @@ interface SpecResult { error: string | null; } +const require = createRequire(import.meta.url); +const generatedRoots = new Map(); + +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") @@ -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}`); @@ -178,17 +190,10 @@ async function importClass( generatedDir: string, className: string, ): Promise { - 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( @@ -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) => @@ -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", @@ -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; @@ -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; @@ -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 = @@ -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, diff --git a/tools/dynwinrt-codegen/E2E_TEST.md b/tools/dynwinrt-codegen/E2E_TEST.md index 0b1e7877..b949e28f 100644 --- a/tools/dynwinrt-codegen/E2E_TEST.md +++ b/tools/dynwinrt-codegen/E2E_TEST.md @@ -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) diff --git a/tools/dynwinrt-codegen/README.md b/tools/dynwinrt-codegen/README.md index 828a27af..00f1c10b 100644 --- a/tools/dynwinrt-codegen/README.md +++ b/tools/dynwinrt-codegen/README.md @@ -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 diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/javascript/ir.rs b/tools/dynwinrt-codegen/src/codegen/winrt/javascript/ir.rs index 919a0ce5..3403bc03 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/javascript/ir.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/javascript/ir.rs @@ -65,8 +65,10 @@ pub enum ProjectedMember { Symbol(ProjectedSymbol), /// `.as()` generic cast AsCast, - /// `.close()` from IClosable - Close, + /// `.close()` from the projected IClosable interface. + Close { + interface_name: String, + }, } #[derive(Clone)] diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/javascript/method.rs b/tools/dynwinrt-codegen/src/codegen/winrt/javascript/method.rs index 78fa48d1..610e70f9 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/javascript/method.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/javascript/method.rs @@ -27,9 +27,12 @@ fn ts_param_type(typ: &TypeMeta) -> String { TypeMeta::RuntimeClass { name, .. } | TypeMeta::Enum { name, .. } | TypeMeta::Interface { name, .. } => name.clone(), - TypeMeta::Parameterized { name, args, .. } => { - crate::meta::make_parameterized_name(name, args) - } + TypeMeta::Parameterized { + namespace, + name, + piid, + args, + } => super::projected_parameterized_name(namespace, name, piid, args), TypeMeta::Array(_) => "DynWinRtArray".to_string(), TypeMeta::Object => "unknown".to_string(), TypeMeta::Delegate { .. } => "DynWinRtValue".to_string(), @@ -43,9 +46,12 @@ pub(crate) fn ts_param_type_safe(typ: &TypeMeta, known: &HashSet) -> Str if let Some(inner) = ireference_inner_type(typ) { let native = ts_return_type_safe(Some(inner), false, known); let wrapper = match typ { - TypeMeta::Parameterized { name, args, .. } => { - crate::meta::make_parameterized_name(name, args) - } + TypeMeta::Parameterized { + namespace, + name, + piid, + args, + } => super::projected_parameterized_name(namespace, name, piid, args), _ => unreachable!(), }; return format!("{} | null | {}", native, wrapper); @@ -211,8 +217,13 @@ fn ts_return_type(typ: Option<&TypeMeta>, is_async: bool) -> String { name.clone() }; } - Some(TypeMeta::Parameterized { name, args, .. }) => { - let s = crate::meta::make_parameterized_name(name, args); + Some(TypeMeta::Parameterized { + namespace, + name, + piid, + args, + }) => { + let s = super::projected_parameterized_name(namespace, name, piid, args); return if is_async { format!("Promise<{}>", s) } else { diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/javascript/mod.rs b/tools/dynwinrt-codegen/src/codegen/winrt/javascript/mod.rs index 5aef747f..2646ae43 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/javascript/mod.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/javascript/mod.rs @@ -10,3 +10,1620 @@ pub mod project; pub mod render; pub(crate) mod signature; pub(crate) mod structs; + +use std::cell::RefCell; +use std::collections::{BTreeMap, BTreeSet, HashMap}; +use std::path::{Component, Path, PathBuf}; + +use crate::meta::{ClassMeta, InterfaceMeta, MethodMeta}; +use crate::types::{TypeKind, TypeMeta, TypeRef}; +use serde::{Deserialize, Serialize}; + +use self::ir::ProjectedFile; +use super::shared::structs::{collect_used_structs_from_class, collect_used_structs_from_iface}; + +#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)] +#[serde(rename_all = "lowercase")] +pub enum JavaScriptTypeKind { + Class, + Interface, + Delegate, + Enum, +} + +impl JavaScriptTypeKind { + pub fn as_str(self) -> &'static str { + match self { + Self::Class => "class", + Self::Interface => "interface", + Self::Delegate => "delegate", + Self::Enum => "enum", + } + } +} + +impl From for JavaScriptTypeKind { + fn from(value: TypeKind) -> Self { + match value { + TypeKind::Class => Self::Class, + TypeKind::Interface => Self::Interface, + TypeKind::Enum => Self::Enum, + } + } +} + +#[derive(Clone, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)] +pub struct JavaScriptTypeIdentity { + pub namespace: String, + pub name: String, + pub kind: JavaScriptTypeKind, + pub variant: String, +} + +impl JavaScriptTypeIdentity { + pub fn new(namespace: &str, name: &str, kind: JavaScriptTypeKind) -> Self { + Self { + namespace: namespace.into(), + name: name.into(), + kind, + variant: String::new(), + } + } + + pub fn with_variant( + namespace: &str, + name: &str, + kind: JavaScriptTypeKind, + variant: &str, + ) -> Self { + Self { + namespace: namespace.into(), + name: name.into(), + kind, + variant: variant.into(), + } + } + + pub fn to_inventory_line(&self) -> String { + format!("{}|{}|{}", self.kind.as_str(), self.namespace, self.name) + } + + fn is_safe(&self) -> bool { + !self.namespace.is_empty() + && self + .namespace + .split('.') + .all(|segment| !segment.is_empty() && is_metadata_identifier(segment)) + && is_metadata_identifier(&self.name) + && self + .variant + .chars() + .all(|character| character.is_ascii_graphic() && character != '|') + } +} + +#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] +pub struct JavaScriptTypeLayoutRecord { + pub identity: JavaScriptTypeIdentity, + pub projected_name: String, + pub implementation_name: String, + pub abi_identity: String, + #[serde(default)] + pub compatibility_aliases: BTreeSet, +} + +impl JavaScriptTypeLayoutRecord { + pub fn new( + identity: JavaScriptTypeIdentity, + projected_name: impl Into, + abi_identity: impl Into, + ) -> Self { + let projected_name = projected_name.into(); + Self { + identity, + implementation_name: projected_name.clone(), + projected_name, + abi_identity: abi_identity.into(), + compatibility_aliases: BTreeSet::new(), + } + } + + pub fn with_compatibility_aliases(mut self, aliases: impl IntoIterator) -> Self { + self.compatibility_aliases.extend(aliases); + self + } + + pub fn with_implementation_name(mut self, implementation_name: impl Into) -> Self { + self.implementation_name = implementation_name.into(); + self + } + + fn is_safe(&self) -> bool { + self.identity.is_safe() + && is_metadata_identifier(&self.projected_name) + && is_metadata_identifier(&self.implementation_name) + && !self.abi_identity.is_empty() + && self + .abi_identity + .chars() + .all(|character| character.is_ascii_graphic() && character != '|') + && self + .compatibility_aliases + .iter() + .all(|alias| is_metadata_identifier(alias)) + } +} + +fn is_metadata_identifier(value: &str) -> bool { + !value.is_empty() + && value + .chars() + .all(|character| character.is_ascii_alphanumeric() || character == '_') +} + +#[derive(Clone, Debug)] +pub struct JavaScriptOutputTarget { + pub identity: JavaScriptTypeIdentity, + pub projected_name: String, + pub canonical_module: String, + pub collides: bool, + pub compatibility_aliases: BTreeSet, +} + +#[derive(Default)] +struct JavaScriptModuleLayout { + targets: BTreeMap, + by_projected_name: HashMap, +} + +thread_local! { + static MODULE_LAYOUT: RefCell> = const { RefCell::new(None) }; +} + +pub struct JavaScriptModuleLayoutGuard { + previous: Option, +} + +impl Drop for JavaScriptModuleLayoutGuard { + fn drop(&mut self) { + MODULE_LAYOUT.with(|layout| { + *layout.borrow_mut() = self.previous.take(); + }); + } +} + +fn pascal_segment(segment: &str) -> String { + let mut result = String::new(); + let mut uppercase_next = true; + for character in segment.chars() { + if !character.is_ascii_alphanumeric() { + uppercase_next = true; + continue; + } + if uppercase_next { + result.push(character.to_ascii_uppercase()); + uppercase_next = false; + } else { + result.push(character); + } + } + result +} + +fn namespace_qualifier(namespace: &str) -> String { + let segments = namespace + .split('.') + .filter(|segment| !segment.is_empty()) + .collect::>(); + let skip = if segments.starts_with(&["Microsoft", "UI"]) + || segments.starts_with(&["Microsoft", "Windows"]) + { + 2 + } else if segments.first() == Some(&"Windows") { + 1 + } else { + 0 + }; + let selected = if skip < segments.len() { + &segments[skip..] + } else { + &segments[..] + }; + selected + .iter() + .map(|segment| pascal_segment(segment)) + .collect() +} + +fn fnv1a64(value: &str) -> u64 { + value + .as_bytes() + .iter() + .fold(0xcbf29ce484222325, |hash, byte| { + (hash ^ u64::from(*byte)).wrapping_mul(0x100000001b3) + }) +} + +fn bounded_identifier(candidate: String, identity: &JavaScriptTypeIdentity) -> String { + const MAX_IDENTIFIER_LENGTH: usize = 120; + if candidate.chars().count() <= MAX_IDENTIFIER_LENGTH { + return candidate; + } + let key = format!( + "{}|{}|{}|{}", + identity.kind.as_str(), + identity.namespace, + identity.name, + identity.variant, + ); + let suffix = format!("_{:08x}", fnv1a64(&key) as u32); + let keep = MAX_IDENTIFIER_LENGTH - suffix.len(); + format!( + "{}{}", + candidate.chars().take(keep).collect::(), + suffix + ) +} + +fn named_identity_token(namespace: &str, name: &str) -> String { + let native_name = metadata_type_name(namespace, name); + let namespace_token = namespace + .split('.') + .filter(|segment| !segment.is_empty()) + .map(pascal_segment) + .collect::(); + format!("{namespace_token}{native_name}") +} + +fn generic_type_token(typ: &TypeMeta) -> String { + match typ { + TypeMeta::Bool => "Boolean".into(), + TypeMeta::I8 => "Int8".into(), + TypeMeta::U8 => "UInt8".into(), + TypeMeta::I16 => "Int16".into(), + TypeMeta::U16 => "UInt16".into(), + TypeMeta::I32 => "Int32".into(), + TypeMeta::U32 => "UInt32".into(), + TypeMeta::I64 => "Int64".into(), + TypeMeta::U64 => "UInt64".into(), + TypeMeta::F32 => "Single".into(), + TypeMeta::F64 => "Double".into(), + TypeMeta::String => "String".into(), + TypeMeta::Char16 => "Char16".into(), + TypeMeta::Guid => "Guid".into(), + TypeMeta::Object => "Object".into(), + TypeMeta::Interface { + namespace, name, .. + } + | TypeMeta::RuntimeClass { + namespace, name, .. + } + | TypeMeta::Delegate { + namespace, name, .. + } + | TypeMeta::Struct { + namespace, name, .. + } + | TypeMeta::Enum { + namespace, name, .. + } => named_identity_token(namespace, name), + TypeMeta::Parameterized { + namespace, + name, + piid, + args, + .. + } => format!( + "{}{}", + namespace + .split('.') + .filter(|segment| !segment.is_empty()) + .map(pascal_segment) + .collect::(), + parameterized_name(namespace, name, piid, args) + ), + TypeMeta::Array(inner) => format!("Array{}", generic_type_token(inner)), + TypeMeta::AsyncAction => "AsyncAction".into(), + TypeMeta::AsyncActionWithProgress(progress) => { + format!("AsyncActionWithProgress{}", generic_type_token(progress)) + } + TypeMeta::AsyncOperation(result) => { + format!("AsyncOperation{}", generic_type_token(result)) + } + TypeMeta::AsyncOperationWithProgress(result, progress) => format!( + "AsyncOperationWithProgress{}{}", + generic_type_token(result), + generic_type_token(progress) + ), + } +} + +fn generic_identity_signature(typ: &TypeMeta) -> String { + match typ { + TypeMeta::Bool => "bool".into(), + TypeMeta::I8 => "i8".into(), + TypeMeta::U8 => "u8".into(), + TypeMeta::I16 => "i16".into(), + TypeMeta::U16 => "u16".into(), + TypeMeta::I32 => "i32".into(), + TypeMeta::U32 => "u32".into(), + TypeMeta::I64 => "i64".into(), + TypeMeta::U64 => "u64".into(), + TypeMeta::F32 => "f32".into(), + TypeMeta::F64 => "f64".into(), + TypeMeta::String => "string".into(), + TypeMeta::Char16 => "char16".into(), + TypeMeta::Guid => "guid".into(), + TypeMeta::Object => "object".into(), + TypeMeta::Interface { + namespace, name, .. + } => format!( + "interface:{namespace}.{}", + metadata_type_name(namespace, name) + ), + TypeMeta::RuntimeClass { + namespace, name, .. + } => format!("class:{namespace}.{}", metadata_type_name(namespace, name)), + TypeMeta::Delegate { + namespace, name, .. + } => format!( + "delegate:{namespace}.{}", + metadata_type_name(namespace, name) + ), + TypeMeta::Struct { + namespace, name, .. + } => format!("struct:{namespace}.{}", metadata_type_name(namespace, name)), + TypeMeta::Enum { + namespace, name, .. + } => format!("enum:{namespace}.{}", metadata_type_name(namespace, name)), + TypeMeta::Parameterized { + namespace, + name, + args, + .. + } => format!( + "generic:{namespace}.{name}<{}>", + args.iter() + .map(generic_identity_signature) + .collect::>() + .join(",") + ), + TypeMeta::Array(inner) => format!("array:{}", generic_identity_signature(inner)), + TypeMeta::AsyncAction => "async-action".into(), + TypeMeta::AsyncActionWithProgress(progress) => { + format!( + "async-action-progress:{}", + generic_identity_signature(progress) + ) + } + TypeMeta::AsyncOperation(result) => { + format!("async-operation:{}", generic_identity_signature(result)) + } + TypeMeta::AsyncOperationWithProgress(result, progress) => format!( + "async-operation-progress:{},{}", + generic_identity_signature(result), + generic_identity_signature(progress) + ), + } +} + +fn normalized_guid(value: &str) -> String { + value + .trim_matches(|character| character == '{' || character == '}') + .to_ascii_lowercase() +} + +fn type_abi_signature(typ: &TypeMeta) -> String { + match typ { + TypeMeta::Bool => "bool".into(), + TypeMeta::I8 => "i8".into(), + TypeMeta::U8 => "u8".into(), + TypeMeta::I16 => "i16".into(), + TypeMeta::U16 => "u16".into(), + TypeMeta::I32 => "i32".into(), + TypeMeta::U32 => "u32".into(), + TypeMeta::I64 => "i64".into(), + TypeMeta::U64 => "u64".into(), + TypeMeta::F32 => "f32".into(), + TypeMeta::F64 => "f64".into(), + TypeMeta::Char16 => "char16".into(), + TypeMeta::String => "string".into(), + TypeMeta::Guid => "guid".into(), + TypeMeta::Object => "object".into(), + TypeMeta::Interface { + namespace, + name, + iid, + } => format!( + "interface({namespace}.{},{})", + metadata_type_name(namespace, name), + normalized_guid(iid) + ), + TypeMeta::RuntimeClass { + namespace, + name, + default_interface, + } => format!( + "class({namespace}.{};default={})", + metadata_type_name(namespace, name), + default_interface + .as_deref() + .map(type_abi_signature) + .unwrap_or_else(|| "none".into()) + ), + TypeMeta::Delegate { + namespace, + name, + iid, + } => format!( + "delegate({namespace}.{},{})", + metadata_type_name(namespace, name), + normalized_guid(iid) + ), + TypeMeta::AsyncAction => "async-action".into(), + TypeMeta::AsyncActionWithProgress(progress) => { + format!( + "async-action-with-progress({})", + type_abi_signature(progress) + ) + } + TypeMeta::AsyncOperation(result) => { + format!("async-operation({})", type_abi_signature(result)) + } + TypeMeta::AsyncOperationWithProgress(result, progress) => format!( + "async-operation-with-progress({},{})", + type_abi_signature(result), + type_abi_signature(progress) + ), + TypeMeta::Parameterized { + namespace, + name, + piid, + args, + } => format!( + "parameterized({namespace}.{name},{},[{}])", + normalized_guid(piid), + args.iter() + .map(type_abi_signature) + .collect::>() + .join(",") + ), + TypeMeta::Array(element) => format!("array({})", type_abi_signature(element)), + TypeMeta::Struct { + namespace, + name, + fields, + } => format!( + "struct({namespace}.{};fields=[{}])", + metadata_type_name(namespace, name), + fields + .iter() + .map(|field| format!("{}:{}", field.name, type_abi_signature(&field.typ))) + .collect::>() + .join(",") + ), + TypeMeta::Enum { + namespace, + name, + underlying, + .. + } => format!( + "enum({namespace}.{};underlying={})", + metadata_type_name(namespace, name), + type_abi_signature(underlying) + ), + } +} + +pub fn parameterized_abi_identity(piid: &str, iid: &str, args: &[TypeMeta]) -> String { + format!( + "piid:{}:iid:{}:args:[{}]", + normalized_guid(piid), + normalized_guid(iid), + args.iter() + .map(type_abi_signature) + .collect::>() + .join(",") + ) +} + +pub fn parameterized_reference_identity(piid: &str, args: &[TypeMeta]) -> String { + format!( + "piid:{}:args:[{}]", + normalized_guid(piid), + args.iter() + .map(type_abi_signature) + .collect::>() + .join(",") + ) +} + +pub fn interface_abi_identity(interface: &InterfaceMeta) -> String { + match &interface.generic_piid { + Some(piid) => parameterized_abi_identity(piid, &interface.iid, &interface.generic_args), + None => format!("iid:{}", normalized_guid(&interface.iid)), + } +} + +pub fn parameterized_name( + namespace: &str, + generic_name: &str, + piid: &str, + args: &[TypeMeta], +) -> String { + let base = generic_name.split('`').next().unwrap_or(generic_name); + let readable = format!( + "{}_{}", + base, + args.iter() + .map(generic_type_token) + .collect::>() + .join("_") + ); + let signature = format!( + "{namespace}.{base}:{}<{}>", + normalized_guid(piid), + args.iter() + .map(generic_identity_signature) + .collect::>() + .join(",") + ); + let requires_identity_suffix = !matches!( + namespace, + "Windows.Foundation" | "Windows.Foundation.Collections" + ) || args.iter().any(|argument| { + !matches!( + argument, + TypeMeta::Bool + | TypeMeta::I8 + | TypeMeta::U8 + | TypeMeta::I16 + | TypeMeta::U16 + | TypeMeta::I32 + | TypeMeta::U32 + | TypeMeta::I64 + | TypeMeta::U64 + | TypeMeta::F32 + | TypeMeta::F64 + | TypeMeta::String + | TypeMeta::Char16 + | TypeMeta::Guid + | TypeMeta::Object + ) + }); + if !requires_identity_suffix { + return readable; + } + let suffix = format!("_g{:016x}", fnv1a64(&signature)); + const MAX_IDENTIFIER_LENGTH: usize = 120; + let keep = MAX_IDENTIFIER_LENGTH - suffix.len(); + format!( + "{}{}", + readable.chars().take(keep).collect::(), + suffix + ) +} + +pub fn parameterized_interface_base_name(interface_name: &str, args: &[TypeMeta]) -> String { + let legacy_suffix = crate::meta::make_parameterized_name("", args); + interface_name + .strip_suffix(&legacy_suffix) + .or_else(|| interface_name.split_once('_').map(|(base, _)| base)) + .unwrap_or(interface_name) + .into() +} + +pub fn parameterized_interface_name( + namespace: &str, + interface_name: &str, + piid: &str, + args: &[TypeMeta], +) -> String { + parameterized_name( + namespace, + ¶meterized_interface_base_name(interface_name, args), + piid, + args, + ) +} + +pub fn projected_parameterized_name( + namespace: &str, + generic_name: &str, + piid: &str, + args: &[TypeMeta], +) -> String { + let output_name = parameterized_name(namespace, generic_name, piid, args); + let variant = parameterized_reference_identity(piid, args); + target_for_identity(&JavaScriptTypeIdentity::with_variant( + namespace, + &output_name, + JavaScriptTypeKind::Interface, + &variant, + )) + .or_else(|| { + target_for_identity(&JavaScriptTypeIdentity::with_variant( + namespace, + &output_name, + JavaScriptTypeKind::Delegate, + &variant, + )) + }) + .map_or(output_name, |target| target.projected_name) +} + +fn namespace_path(namespace: &str) -> String { + namespace + .split('.') + .filter(|segment| !segment.is_empty()) + .map(|segment| { + let mut result = String::new(); + let chars = segment.chars().collect::>(); + for (index, character) in chars.iter().copied().enumerate() { + if !character.is_ascii_alphanumeric() { + if !result.ends_with('-') { + result.push('-'); + } + continue; + } + let previous_is_lower_or_digit = index > 0 + && (chars[index - 1].is_ascii_lowercase() || chars[index - 1].is_ascii_digit()); + let next_is_lower = chars + .get(index + 1) + .is_some_and(|next| next.is_ascii_lowercase()); + if character.is_ascii_uppercase() + && !result.is_empty() + && (previous_is_lower_or_digit || next_is_lower) + && !result.ends_with('-') + { + result.push('-'); + } + result.push(character.to_ascii_lowercase()); + } + result.trim_matches('-').to_string() + }) + .collect::>() + .join("/") +} + +fn qualified_projected_name(identity: &JavaScriptTypeIdentity) -> String { + let qualifier = namespace_qualifier(&identity.namespace); + let candidate = if qualifier.is_empty() { + format!( + "{}{}", + pascal_segment(identity.kind.as_str()), + identity.name + ) + } else { + format!("{qualifier}{}", identity.name) + }; + bounded_identifier(candidate, identity) +} + +fn disambiguated_projected_name(identity: &JavaScriptTypeIdentity) -> String { + let namespace = identity + .namespace + .split('.') + .map(pascal_segment) + .collect::(); + bounded_identifier( + format!( + "{namespace}{}{}", + identity.name, + pascal_segment(identity.kind.as_str()) + ), + identity, + ) +} + +fn hashed_projected_name(candidate: String, identity: &JavaScriptTypeIdentity) -> String { + let suffix = format!( + "_{:08x}", + fnv1a64(&format!( + "{}|{}|{}|{}", + identity.kind.as_str(), + identity.namespace, + identity.name, + identity.variant, + )) as u32 + ); + let keep = 120usize.saturating_sub(suffix.len()); + format!( + "{}{}", + candidate.chars().take(keep).collect::(), + suffix + ) +} + +pub fn install_javascript_module_layout( + identities: impl IntoIterator, +) -> Result { + install_javascript_module_layout_with_records( + identities, + std::iter::empty::(), + ) +} + +pub fn install_javascript_module_layout_with_records( + identities: impl IntoIterator, + previous_records: impl IntoIterator, +) -> Result { + let identities = identities.into_iter().collect::>(); + if let Some(identity) = identities.iter().find(|identity| !identity.is_safe()) { + return Err(format!( + "Unsafe JavaScript type identity `{}`", + identity.to_inventory_line() + )); + } + let mut counts = HashMap::::new(); + for identity in &identities { + *counts.entry(identity.name.clone()).or_default() += 1; + } + + let mut previous_by_identity = BTreeMap::new(); + for record in previous_records { + if !record.is_safe() || !identities.contains(&record.identity) { + return Err(format!( + "Invalid previous JavaScript module layout record `{:?}`", + record + )); + } + let identity = record.identity.clone(); + if previous_by_identity + .insert(identity.clone(), record) + .is_some() + { + return Err(format!( + "Duplicate previous JavaScript module layout record for `{}.{}`", + identity.namespace, identity.name, + )); + } + } + + let mut projected_names = BTreeMap::new(); + let mut normalized_projected_owners = HashMap::::new(); + + // Assign collision-derived names first so a unique native short name can + // never claim another type's natural qualified name in a fresh layout. + for colliding_pass in [true, false] { + for identity in identities + .iter() + .filter(|identity| (counts[&identity.name] > 1) == colliding_pass) + { + if projected_names.contains_key(identity) { + continue; + } + let mut projected = if colliding_pass { + qualified_projected_name(identity) + } else { + identity.name.clone() + }; + if normalized_projected_owners.contains_key(&projected.to_ascii_lowercase()) { + projected = disambiguated_projected_name(identity); + } + if normalized_projected_owners.contains_key(&projected.to_ascii_lowercase()) { + projected = hashed_projected_name(projected, identity); + } + let normalized = projected.to_ascii_lowercase(); + if let Some(existing) = normalized_projected_owners.get(&normalized) { + return Err(format!( + "JavaScript projected name collision: `{}.{}` and `{}.{}` both map to `{projected}`", + existing.namespace, existing.name, identity.namespace, identity.name + )); + } + normalized_projected_owners.insert(normalized, identity.clone()); + projected_names.insert(identity.clone(), projected); + } + } + + let mut targets = BTreeMap::new(); + let mut module_owners = HashMap::::new(); + for identity in identities { + let projected_name = projected_names[&identity].clone(); + let namespace = namespace_path(&identity.namespace); + let canonical_module = if namespace.is_empty() { + identity.name.clone() + } else { + format!("{namespace}/{}", identity.name) + }; + let normalized_module = canonical_module.to_ascii_lowercase(); + if let Some(existing) = module_owners.insert(normalized_module, identity.clone()) { + return Err(format!( + "JavaScript canonical module collision: `{}.{}` and `{}.{}` both map to `{canonical_module}`", + existing.namespace, existing.name, identity.namespace, identity.name + )); + } + let mut compatibility_aliases = previous_by_identity + .get(&identity) + .map(|record| record.compatibility_aliases.clone()) + .unwrap_or_default(); + if let Some(previous) = previous_by_identity.get(&identity) + && previous.projected_name != projected_name + { + compatibility_aliases.insert(previous.projected_name.clone()); + } + compatibility_aliases.remove(&projected_name); + compatibility_aliases.remove(&identity.name); + let target = JavaScriptOutputTarget { + identity: identity.clone(), + projected_name: projected_name.clone(), + canonical_module, + collides: counts[&identity.name] > 1 || projected_name != identity.name, + compatibility_aliases, + }; + targets.insert(identity, target); + } + let projected_owners = projected_names + .into_iter() + .map(|(identity, projected)| (projected, identity)) + .collect(); + + let previous = MODULE_LAYOUT.with(|layout| { + layout.borrow_mut().replace(JavaScriptModuleLayout { + targets, + by_projected_name: projected_owners, + }) + }); + Ok(JavaScriptModuleLayoutGuard { previous }) +} + +pub fn javascript_module_layout_installed() -> bool { + MODULE_LAYOUT.with(|layout| layout.borrow().is_some()) +} + +pub fn javascript_layout_identities() -> Vec { + MODULE_LAYOUT.with(|layout| { + layout + .borrow() + .as_ref() + .map(|layout| layout.targets.keys().cloned().collect()) + .unwrap_or_default() + }) +} + +pub fn javascript_output_targets() -> Vec { + MODULE_LAYOUT.with(|layout| { + layout + .borrow() + .as_ref() + .map(|layout| layout.targets.values().cloned().collect()) + .unwrap_or_default() + }) +} + +fn target_for_identity(identity: &JavaScriptTypeIdentity) -> Option { + MODULE_LAYOUT.with(|layout| { + layout + .borrow() + .as_ref() + .and_then(|layout| layout.targets.get(identity).cloned()) + }) +} + +pub fn javascript_output_target(projected_name: &str) -> Option { + MODULE_LAYOUT.with(|layout| { + let layout = layout.borrow(); + let layout = layout.as_ref()?; + let identity = layout.by_projected_name.get(projected_name)?; + layout.targets.get(identity).cloned() + }) +} + +fn projected_name(namespace: &str, name: &str, kind: JavaScriptTypeKind) -> String { + target_for_identity(&JavaScriptTypeIdentity::new(namespace, name, kind)) + .or_else(|| { + if kind == JavaScriptTypeKind::Interface { + target_for_identity(&JavaScriptTypeIdentity::new( + namespace, + name, + JavaScriptTypeKind::Delegate, + )) + } else { + None + } + }) + .map_or_else(|| name.into(), |target| target.projected_name) +} + +pub(crate) fn metadata_type_name(namespace: &str, output_name: &str) -> String { + MODULE_LAYOUT.with(|layout| { + layout + .borrow() + .as_ref() + .and_then(|layout| { + let identity = layout.by_projected_name.get(output_name)?; + (identity.namespace == namespace).then(|| identity.name.clone()) + }) + .unwrap_or_else(|| output_name.into()) + }) +} + +fn apply_projected_type_names(typ: &mut TypeMeta) { + match typ { + TypeMeta::Interface { + namespace, name, .. + } => *name = projected_name(namespace, name, JavaScriptTypeKind::Interface), + TypeMeta::Delegate { + namespace, name, .. + } => *name = projected_name(namespace, name, JavaScriptTypeKind::Delegate), + TypeMeta::RuntimeClass { + namespace, + name, + default_interface, + } => { + *name = projected_name(namespace, name, JavaScriptTypeKind::Class); + if let Some(default_interface) = default_interface { + apply_projected_type_names(default_interface); + } + } + TypeMeta::AsyncActionWithProgress(inner) + | TypeMeta::AsyncOperation(inner) + | TypeMeta::Array(inner) => apply_projected_type_names(inner), + TypeMeta::AsyncOperationWithProgress(result, progress) => { + apply_projected_type_names(result); + apply_projected_type_names(progress); + } + TypeMeta::Parameterized { args, .. } => { + for argument in args { + apply_projected_type_names(argument); + } + } + TypeMeta::Struct { fields, .. } => { + for field in fields { + apply_projected_type_names(&mut field.typ); + } + } + TypeMeta::Enum { + namespace, + name, + underlying, + .. + } => { + *name = projected_name(namespace, name, JavaScriptTypeKind::Enum); + apply_projected_type_names(underlying); + } + _ => {} + } +} + +fn apply_projected_method_names(method: &mut MethodMeta) { + for parameter in &mut method.params { + apply_projected_type_names(&mut parameter.typ); + } + if let Some(return_type) = &mut method.return_type { + apply_projected_type_names(return_type); + } +} + +fn apply_projected_interface_names(interface: &mut InterfaceMeta) { + let kind = if interface + .methods + .iter() + .any(|method| method.name == ".ctor") + && interface + .methods + .iter() + .any(|method| method.name == "Invoke") + { + JavaScriptTypeKind::Delegate + } else { + JavaScriptTypeKind::Interface + }; + interface.name = if let Some(piid) = &interface.generic_piid { + let output_name = parameterized_interface_name( + &interface.namespace, + &interface.name, + piid, + &interface.generic_args, + ); + let variant = parameterized_reference_identity(piid, &interface.generic_args); + target_for_identity(&JavaScriptTypeIdentity::with_variant( + &interface.namespace, + &output_name, + kind, + &variant, + )) + .map_or(output_name, |target| target.projected_name) + } else { + projected_name(&interface.namespace, &interface.name, kind) + }; + for base in &mut interface.base_interfaces { + apply_projected_type_names(base); + } + for argument in &mut interface.generic_args { + apply_projected_type_names(argument); + } + for method in &mut interface.methods { + apply_projected_method_names(method); + } +} + +fn apply_projected_type_ref_name(reference: &mut TypeRef) { + reference.name = projected_name(&reference.namespace, &reference.name, reference.kind.into()); +} + +fn apply_projected_class_names(class: &mut ClassMeta) { + class.name = projected_name(&class.namespace, &class.name, JavaScriptTypeKind::Class); + if let Some(base_class) = &mut class.base_class { + apply_projected_type_ref_name(base_class); + } + if let Some(default_interface) = &mut class.default_interface { + apply_projected_interface_names(default_interface); + } + for interface in class + .required_interfaces + .iter_mut() + .chain(class.overridable_interfaces.iter_mut()) + .chain(class.factory_interfaces.iter_mut()) + .chain(class.static_interfaces.iter_mut()) + { + apply_projected_interface_names(interface); + } + for constructor in &mut class.constructors { + if let Some(factory_interface) = &mut constructor.factory_interface { + apply_projected_type_ref_name(factory_interface); + } + } +} + +pub fn apply_javascript_projected_names( + classes: &mut [ClassMeta], + interfaces: &mut [InterfaceMeta], + enums: &mut [TypeMeta], +) { + for class in classes { + apply_projected_class_names(class); + } + for interface in interfaces { + apply_projected_interface_names(interface); + } + for en in enums { + apply_projected_type_names(en); + } +} + +pub fn validate_struct_helper_identities( + classes: &[ClassMeta], + interfaces: &[InterfaceMeta], +) -> Result, String> { + fn validate( + owner: &str, + structs: Vec, + identities: &mut HashMap, + ) -> Result<(), String> { + for structure in structs { + let TypeMeta::Struct { + namespace, name, .. + } = structure + else { + continue; + }; + let identity = format!("{namespace}.{name}"); + if let Some((existing, existing_owner)) = + identities.insert(name.clone(), (identity.clone(), owner.to_string())) + && existing != identity + { + return Err(format!( + "JavaScript struct helper collision: `{existing}` from `{existing_owner}` and \ + `{identity}` from `{owner}` both require `{name}_Type`/`pack{name}`. \ + Generate these bindings into separate output directories." + )); + } + } + Ok(()) + } + + let mut identities = HashMap::new(); + for class in classes { + validate( + &class.full_name, + collect_used_structs_from_class(class), + &mut identities, + )?; + } + for interface in interfaces { + validate( + &format!("{}.{}", interface.namespace, interface.name), + collect_used_structs_from_iface(interface), + &mut identities, + )?; + } + Ok(identities + .into_iter() + .map(|(name, (identity, _))| (name, identity)) + .collect()) +} + +fn relative_module(from_module: &str, to_module: &str) -> String { + let from_parent = Path::new(from_module) + .parent() + .unwrap_or_else(|| Path::new("")); + let from = from_parent.components().collect::>(); + let to = Path::new(to_module).components().collect::>(); + let common = from + .iter() + .zip(&to) + .take_while(|(left, right)| left == right) + .count(); + let mut result = PathBuf::new(); + for _ in common..from.len() { + result.push(".."); + } + for component in &to[common..] { + match component { + Component::Normal(value) => result.push(value), + Component::ParentDir => result.push(".."), + Component::CurDir => {} + Component::Prefix(_) | Component::RootDir => {} + } + } + let result = result.to_string_lossy().replace('\\', "/"); + if result.starts_with("../") { + result + } else { + format!("./{result}") + } +} + +pub fn configure_projected_file(file: &mut ProjectedFile) -> Option { + let target = javascript_output_target(&file.name)?; + for import in &mut file.imports { + if import.is_runtime_package { + if (import.from.starts_with("./") || import.from.starts_with("../")) + && let Some(module) = import + .from + .strip_suffix(".js") + .or(Some(import.from.as_str())) + { + import.from = format!("{}.js", relative_module(&target.canonical_module, module)); + } + continue; + } + let Some(module) = import + .from + .strip_prefix("./") + .and_then(|path| path.strip_suffix(".js")) + else { + continue; + }; + let target_module = javascript_output_target(module) + .map_or_else(|| module.to_string(), |target| target.canonical_module); + import.from = format!( + "{}.js", + relative_module(&target.canonical_module, &target_module) + ); + } + Some(target) +} + +pub fn root_relative_module(from_module: &str, root_module: &str) -> String { + relative_module(from_module, root_module) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::meta::{ParamDirection, ParamMeta}; + + fn runtime_class(namespace: &str, name: &str) -> TypeMeta { + TypeMeta::RuntimeClass { + namespace: namespace.into(), + name: name.into(), + default_interface: Some(Box::new(TypeMeta::Interface { + namespace: namespace.into(), + name: format!("I{name}"), + iid: "11111111-1111-1111-1111-111111111111".into(), + })), + } + } + + #[test] + fn layout_qualifies_collisions_and_preserves_native_identities() { + let identities = [ + JavaScriptTypeIdentity::new( + "Microsoft.UI.Input.DragDrop", + "DragUIOverride", + JavaScriptTypeKind::Class, + ), + JavaScriptTypeIdentity::new( + "Microsoft.UI.Xaml", + "DragUIOverride", + JavaScriptTypeKind::Class, + ), + JavaScriptTypeIdentity::new( + "Microsoft.UI.Composition", + "AnimationDirection", + JavaScriptTypeKind::Enum, + ), + JavaScriptTypeIdentity::new( + "Microsoft.UI.Xaml.Controls.Primitives", + "AnimationDirection", + JavaScriptTypeKind::Enum, + ), + ]; + let _layout = install_javascript_module_layout(identities).unwrap(); + let mut classes = vec![ + ClassMeta { + namespace: "Microsoft.UI.Input.DragDrop".into(), + name: "DragUIOverride".into(), + full_name: "Microsoft.UI.Input.DragDrop.DragUIOverride".into(), + default_interface: Some(InterfaceMeta { + name: "IDragUIOverride".into(), + methods: vec![MethodMeta { + params: vec![ParamMeta { + name: "value".into(), + typ: runtime_class("Microsoft.UI.Input.DragDrop", "DragUIOverride"), + direction: ParamDirection::In, + }], + ..Default::default() + }], + ..Default::default() + }), + ..Default::default() + }, + ClassMeta { + namespace: "Microsoft.UI.Xaml".into(), + name: "DragUIOverride".into(), + full_name: "Microsoft.UI.Xaml.DragUIOverride".into(), + ..Default::default() + }, + ]; + let mut enums = vec![TypeMeta::Enum { + namespace: "Microsoft.UI.Xaml.Controls.Primitives".into(), + name: "AnimationDirection".into(), + underlying: Box::new(TypeMeta::I32), + members: Vec::new(), + is_flags: false, + doc: None, + deprecated: None, + }]; + + apply_javascript_projected_names(&mut classes, &mut [], &mut enums); + + assert_eq!(classes[0].name, "InputDragDropDragUIOverride"); + assert_eq!(classes[1].name, "XamlDragUIOverride"); + assert_eq!( + classes[0].full_name, + "Microsoft.UI.Input.DragDrop.DragUIOverride" + ); + let parameter = &classes[0].default_interface.as_ref().unwrap().methods[0].params[0].typ; + assert!(matches!( + parameter, + TypeMeta::RuntimeClass { name, .. } if name == "InputDragDropDragUIOverride" + )); + assert!( + signature::ts_dynwinrt_type(parameter) + .contains("Microsoft.UI.Input.DragDrop.DragUIOverride") + ); + assert!(matches!( + enums[0], + TypeMeta::Enum { ref name, .. } if name == "XamlControlsPrimitivesAnimationDirection" + )); + assert_eq!( + metadata_type_name("Microsoft.UI.Input.DragDrop", "InputDragDropDragUIOverride"), + "DragUIOverride" + ); + } + + #[test] + fn layout_keeps_unique_short_names() { + let identity = JavaScriptTypeIdentity::new( + "Microsoft.UI.Xaml.Controls", + "Button", + JavaScriptTypeKind::Class, + ); + let _layout = install_javascript_module_layout([identity.clone()]).unwrap(); + let target = target_for_identity(&identity).unwrap(); + + assert_eq!(target.projected_name, "Button"); + assert_eq!(target.canonical_module, "microsoft/ui/xaml/controls/Button"); + assert!(!target.collides); + } + + #[test] + fn nested_layout_guard_restores_previous_layout() { + let button = JavaScriptTypeIdentity::new( + "Microsoft.UI.Xaml.Controls", + "Button", + JavaScriptTypeKind::Class, + ); + let uri = + JavaScriptTypeIdentity::new("Windows.Foundation", "Uri", JavaScriptTypeKind::Class); + let _outer = install_javascript_module_layout([button.clone()]).unwrap(); + assert!(target_for_identity(&button).is_some()); + { + let _inner = install_javascript_module_layout([uri.clone()]).unwrap(); + assert!(target_for_identity(&button).is_none()); + assert!(target_for_identity(&uri).is_some()); + } + assert!(target_for_identity(&button).is_some()); + assert!(target_for_identity(&uri).is_none()); + } + + #[test] + fn parameterized_names_include_complete_named_argument_identity() { + let windows_pointer = TypeMeta::RuntimeClass { + namespace: "Windows.UI.Input".into(), + name: "PointerPoint".into(), + default_interface: None, + }; + let winui_pointer = TypeMeta::RuntimeClass { + namespace: "Microsoft.UI.Input".into(), + name: "PointerPoint".into(), + default_interface: None, + }; + + let windows_name = parameterized_name( + "Windows.Foundation.Collections", + "IVector`1", + "vector", + &[windows_pointer], + ); + let winui_name = parameterized_name( + "Windows.Foundation.Collections", + "IVector", + "vector", + &[winui_pointer], + ); + assert!( + windows_name.starts_with("IVector_WindowsUIInputPointerPoint_g"), + "{windows_name}" + ); + assert!( + winui_name.starts_with("IVector_MicrosoftUIInputPointerPoint_g"), + "{winui_name}" + ); + assert_ne!(windows_name, winui_name); + assert_eq!( + parameterized_name( + "Windows.Foundation.Collections", + "IMap", + "map", + &[TypeMeta::String, TypeMeta::Object], + ), + "IMap_String_Object" + ); + } + + #[test] + fn parameterized_names_recursively_encode_nested_generics() { + let nested = TypeMeta::Parameterized { + namespace: "Windows.Foundation.Collections".into(), + name: "IVector`1".into(), + piid: "vector".into(), + args: vec![TypeMeta::RuntimeClass { + namespace: "Contoso.Models".into(), + name: "Widget".into(), + default_interface: None, + }], + }; + let name = parameterized_name( + "Windows.Foundation.Collections", + "IIterable`1", + "iterable", + &[nested], + ); + + assert!( + name.starts_with("IIterable_WindowsFoundationCollectionsIVector_ContosoModelsWidget_g"), + "{name}" + ); + } + + #[test] + fn parameterized_identity_suffix_disambiguates_namespace_boundaries() { + let first = TypeMeta::RuntimeClass { + namespace: "A.B".into(), + name: "C".into(), + default_interface: None, + }; + let second = TypeMeta::RuntimeClass { + namespace: "A".into(), + name: "BC".into(), + default_interface: None, + }; + let first_name = parameterized_name( + "Windows.Foundation.Collections", + "IVector", + "vector", + &[first], + ); + let second_name = parameterized_name( + "Windows.Foundation.Collections", + "IVector", + "vector", + &[second], + ); + + assert!(first_name.starts_with("IVector_ABC_g"), "{first_name}"); + assert!(second_name.starts_with("IVector_ABC_g"), "{second_name}"); + assert_ne!(first_name, second_name); + } + + #[test] + fn generic_abi_identity_includes_runtime_and_struct_signatures() { + let runtime = |iid: &str| TypeMeta::RuntimeClass { + namespace: "Contoso".into(), + name: "Widget".into(), + default_interface: Some(Box::new(TypeMeta::Interface { + namespace: "Contoso".into(), + name: "IWidget".into(), + iid: iid.into(), + })), + }; + let structure = |field_type| TypeMeta::Struct { + namespace: "Contoso".into(), + name: "Payload".into(), + fields: vec![crate::types::FieldMeta { + name: "Value".into(), + typ: field_type, + }], + }; + + assert_ne!( + parameterized_abi_identity("piid", "piid", &[runtime("iid-one")]), + parameterized_abi_identity("piid", "piid", &[runtime("iid-two")]) + ); + assert_ne!( + parameterized_abi_identity("piid", "piid", &[structure(TypeMeta::I32)]), + parameterized_abi_identity("piid", "piid", &[structure(TypeMeta::I64)]) + ); + } + + #[test] + fn clean_and_incremental_layouts_use_the_same_second_order_collision_owner() { + let windows = + JavaScriptTypeIdentity::new("Windows.Foundation", "Widget", JavaScriptTypeKind::Class); + let contoso = JavaScriptTypeIdentity::new("Contoso", "Widget", JavaScriptTypeKind::Class); + let old_layout = + install_javascript_module_layout([windows.clone(), contoso.clone()]).unwrap(); + let records = javascript_output_targets() + .into_iter() + .map(|target| { + JavaScriptTypeLayoutRecord::new(target.identity, target.projected_name, "type") + }) + .collect::>(); + drop(old_layout); + + let microsoft = JavaScriptTypeIdentity::new( + "Microsoft.UI.Foundation", + "Widget", + JavaScriptTypeKind::Class, + ); + let identities = [windows.clone(), contoso.clone(), microsoft.clone()]; + let incremental_layout = + install_javascript_module_layout_with_records(identities.clone(), records).unwrap(); + assert!( + target_for_identity(&windows) + .unwrap() + .compatibility_aliases + .contains("FoundationWidget") + ); + let incremental = identities + .iter() + .map(|identity| { + ( + identity.clone(), + target_for_identity(identity).unwrap().projected_name, + ) + }) + .collect::>(); + drop(incremental_layout); + + let _clean_layout = install_javascript_module_layout(identities.clone()).unwrap(); + let clean = identities + .iter() + .map(|identity| { + ( + identity.clone(), + target_for_identity(identity).unwrap().projected_name, + ) + }) + .collect::>(); + + assert_eq!(incremental, clean); + assert_eq!(clean[µsoft], "FoundationWidget"); + assert_eq!(clean[&windows], "WindowsFoundationWidgetClass"); + } + + #[test] + fn namespace_distinct_struct_helpers_fail_closed_before_projection() { + let structure = |namespace: &str, typ| TypeMeta::Struct { + namespace: namespace.into(), + name: "Payload".into(), + fields: vec![crate::types::FieldMeta { + name: "Value".into(), + typ, + }], + }; + let class = ClassMeta { + name: "Widget".into(), + namespace: "Contoso".into(), + full_name: "Contoso.Widget".into(), + default_interface: Some(InterfaceMeta { + name: "IWidget".into(), + namespace: "Contoso".into(), + iid: "11111111-1111-1111-1111-111111111111".into(), + methods: vec![MethodMeta { + name: "UsePayloads".into(), + params: vec![ + ParamMeta { + name: "alpha".into(), + typ: structure("Alpha", TypeMeta::I32), + direction: ParamDirection::In, + }, + ParamMeta { + name: "beta".into(), + typ: structure("Beta", TypeMeta::I64), + direction: ParamDirection::In, + }, + ], + ..Default::default() + }], + ..Default::default() + }), + ..Default::default() + }; + + let error = validate_struct_helper_identities(&[class], &[]) + .expect_err("namespace-distinct short struct names must fail closed"); + + assert!(error.contains("Alpha.Payload"), "{error}"); + assert!(error.contains("Beta.Payload"), "{error}"); + assert!(error.contains("packPayload"), "{error}"); + } + + #[test] + fn relative_modules_point_from_namespace_to_root_and_siblings() { + assert_eq!( + relative_module("microsoft/ui/xaml/controls/Button", "lifetime"), + "../../../../lifetime" + ); + assert_eq!( + relative_module( + "microsoft/ui/xaml/controls/Button", + "microsoft/ui/xaml/Control" + ), + "../Control" + ); + assert_eq!( + relative_module("windows/foundation/Uri", "../runtime"), + "../../../runtime" + ); + } + + #[test] + fn qualified_names_use_stable_bounded_hash_suffixes() { + let name = "VeryLongProjectedTypeName".repeat(8); + let first = JavaScriptTypeIdentity::new( + "Contoso.Extremely.Long.Namespace.For.Generated.Bindings", + &name, + JavaScriptTypeKind::Class, + ); + let second = JavaScriptTypeIdentity::new( + "Fabrikam.Extremely.Long.Namespace.For.Generated.Bindings", + &name, + JavaScriptTypeKind::Class, + ); + + let first_name = qualified_projected_name(&first); + let second_name = qualified_projected_name(&second); + + assert_eq!(first_name.len(), 120); + assert_eq!(second_name.len(), 120); + assert_ne!(first_name, second_name); + assert_eq!(first_name, qualified_projected_name(&first)); + } + + #[test] + fn layout_rejects_unsafe_inventory_identities() { + let identity = + JavaScriptTypeIdentity::new("Contoso", "../outside/Widget", JavaScriptTypeKind::Class); + + let error = install_javascript_module_layout([identity]) + .err() + .expect("path-like metadata names must be rejected"); + + assert!(error.contains("Unsafe JavaScript type identity"), "{error}"); + } +} diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/javascript/project/collections.rs b/tools/dynwinrt-codegen/src/codegen/winrt/javascript/project/collections.rs index 08dcb567..7b04cd3f 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/javascript/project/collections.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/javascript/project/collections.rs @@ -559,7 +559,12 @@ pub(super) fn project_collection_create( } else if piid == PIID_IOBSERVABLE_VECTOR && iface.generic_args.len() == 1 { let elem_type = ts_dynwinrt_type(&iface.generic_args[0]); let elem_ts = ts_param_type_safe(&iface.generic_args[0], known_types); - let vector_name = iface.name.replacen("IObservableVector", "IVector", 1); + let vector_name = super::super::projected_parameterized_name( + crate::meta::WINDOWS_FOUNDATION_COLLECTIONS_NAMESPACE, + "IVector", + PIID_IVECTOR, + &iface.generic_args, + ); imports.push(ProjectedImport { symbols: vec![vector_name.clone()], from: format!("./{}.js", vector_name), @@ -584,8 +589,8 @@ pub(super) fn project_collection_create( is_static: false, invoke_expr: String::new(), sync_return_expr: Some(format!( - "new ((__load_{vector}()).{vector})(this._obj)", - vector = vector_name, + "new {vector}(this._obj)", + vector = ref_marker(&vector_name), )), async_convert_v: None, is_void: false, @@ -621,9 +626,9 @@ pub(super) fn project_collection_create( is_static: true, invoke_expr: String::new(), sync_return_expr: Some(format!( - "(() => {{ const value = DynWinRtValue.createVector(items.map(i => _unwrap(i)), {elem_type}); const observable = new {observable}(value); const vector = new ((__load_{vector}()).{vector})(value); Object.defineProperties(vector, {{ asVector: {{ value: observable.asVector.bind(observable) }}, onVectorChanged: {{ value: observable.onVectorChanged.bind(observable) }}, onceVectorChanged: {{ value: observable.onceVectorChanged.bind(observable) }}, offVectorChanged: {{ value: observable.offVectorChanged.bind(observable) }} }}); return vector; }})()", + "(() => {{ const value = DynWinRtValue.createVector(items.map(i => _unwrap(i)), {elem_type}); const observable = new {observable}(value); const vector = new {vector}(value); Object.defineProperties(vector, {{ asVector: {{ value: observable.asVector.bind(observable) }}, onVectorChanged: {{ value: observable.onVectorChanged.bind(observable) }}, onceVectorChanged: {{ value: observable.onceVectorChanged.bind(observable) }}, offVectorChanged: {{ value: observable.offVectorChanged.bind(observable) }} }}); return vector; }})()", observable = iface.name, - vector = vector_name, + vector = ref_marker(&vector_name), )), async_convert_v: None, is_void: false, diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/javascript/project/methods.rs b/tools/dynwinrt-codegen/src/codegen/winrt/javascript/project/methods.rs index b6e2c9cc..6ab00e91 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/javascript/project/methods.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/javascript/project/methods.rs @@ -29,9 +29,16 @@ fn is_projected_delegate_type(typ: Option<&TypeMeta>, delegate_names: &HashSet true, Some(TypeMeta::Interface { name, .. }) => delegate_names.contains(name), - Some(TypeMeta::Parameterized { name, args, .. }) => { - delegate_names.contains(&crate::meta::make_parameterized_name(name, args)) - } + Some(TypeMeta::Parameterized { + namespace, + name, + piid, + args, + }) => delegate_names.contains( + &crate::codegen::winrt::javascript::projected_parameterized_name( + namespace, name, piid, args, + ), + ), _ => false, } } @@ -1058,9 +1065,16 @@ fn project_event_add( let cap = capitalize(&event_name); let delegate_first_param = in_params.first().map(|p| &p.typ); let delegate_name = delegate_first_param.and_then(|t| match t { - TypeMeta::Parameterized { name, args, .. } => { - Some(crate::meta::make_parameterized_name(name, args)) - } + TypeMeta::Parameterized { + namespace, + name, + piid, + args, + } => Some( + crate::codegen::winrt::javascript::projected_parameterized_name( + namespace, name, piid, args, + ), + ), TypeMeta::Delegate { name, .. } => Some(name.clone()), TypeMeta::Interface { name, .. } => Some(name.clone()), _ => None, diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/javascript/project/mod.rs b/tools/dynwinrt-codegen/src/codegen/winrt/javascript/project/mod.rs index edce23f4..e48acafc 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/javascript/project/mod.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/javascript/project/mod.rs @@ -36,8 +36,7 @@ pub fn get_import_name() -> String { } use crate::codegen::winrt::shared::imports::{ - NO_DEFERRED, collect_iface_type_imports, collect_type_imports, - collect_used_generics_from_class, collect_used_generics_from_methods, fill_array_output_index, + NO_DEFERRED, collect_iface_type_imports, collect_type_imports, fill_array_output_index, fill_array_uses_retval_count, get_in_params, ireference_inner_type, method_abi_output_count, }; use crate::codegen::winrt::shared::structs::{ @@ -53,6 +52,70 @@ use super::signature::{ build_args_expr, collect_runtime_class_iid_consts, convert_array_return, convert_return, generate_interface_registration, js_argument_kind, ref_marker, ts_dynwinrt_type, wrap_arg, }; + +fn visit_projected_generics(typ: &TypeMeta, names: &mut HashSet) { + match typ { + TypeMeta::Parameterized { + namespace, + name, + piid, + args, + } => { + names.insert(super::projected_parameterized_name( + namespace, name, piid, args, + )); + for argument in args { + visit_projected_generics(argument, names); + } + } + TypeMeta::AsyncOperation(inner) + | TypeMeta::AsyncActionWithProgress(inner) + | TypeMeta::Array(inner) => visit_projected_generics(inner, names), + TypeMeta::AsyncOperationWithProgress(result, progress) => { + visit_projected_generics(result, names); + visit_projected_generics(progress, names); + } + TypeMeta::Struct { fields, .. } => { + for field in fields { + visit_projected_generics(&field.typ, names); + } + } + _ => {} + } +} + +fn collect_used_generics_from_methods(methods: &[MethodMeta]) -> Vec { + let mut names = HashSet::new(); + for method in methods { + for parameter in &method.params { + visit_projected_generics(¶meter.typ, &mut names); + } + if let Some(return_type) = &method.return_type { + visit_projected_generics(return_type, &mut names); + } + } + let mut names = names.into_iter().collect::>(); + names.sort(); + names +} + +fn collect_used_generics_from_class(class: &ClassMeta) -> Vec { + let mut names = HashSet::new(); + for method in class + .all_interfaces() + .flat_map(|interface| &interface.methods) + { + for parameter in &method.params { + visit_projected_generics(¶meter.typ, &mut names); + } + if let Some(return_type) = &method.return_type { + visit_projected_generics(return_type, &mut names); + } + } + let mut names = names.into_iter().collect::>(); + names.sort(); + names +} use super::structs::{struct_field_getter, struct_field_setter, ts_struct_field_type}; use collections::{ @@ -224,6 +287,7 @@ pub fn project_class( imports.push(runtime_import); // Collection generics imports + let mut imported_names: HashSet = HashSet::new(); let collection_names = collect_used_generics_from_class(class); for cname in &collection_names { if !all_delegate_names.contains(cname) { @@ -234,6 +298,7 @@ pub fn project_class( dts_only: false, is_runtime_package: false, }); + imported_names.insert(cname.clone()); } } @@ -261,7 +326,6 @@ pub fn project_class( } // Type imports - let mut imported_names: HashSet = HashSet::new(); let type_imports = collect_type_imports(class); let mut sorted_imports: Vec<_> = type_imports.iter().collect(); sorted_imports @@ -343,18 +407,18 @@ pub fn project_class( // IClosable by name. Register the import here so the IID-const loop below // sees `IID_IClosable` in `imported_names` and skips declaring it, // avoiding a duplicate identifier in single-class emission. - let needs_iclosable = class.name != "IClosable" - && class - .required_interfaces - .iter() - .any(|ri| ri.iid == ICLOSABLE_IID); - if needs_iclosable && !imported_names.contains("IClosable") { - imports.push(format_type_import_projected( - "IClosable", - TypeKind::Interface, - )); - imported_names.insert("IClosable".into()); - imported_names.insert("IID_IClosable".into()); + let iclosable_name = class + .required_interfaces + .iter() + .find(|interface| interface.iid == ICLOSABLE_IID) + .map(|interface| interface.name.clone()); + if let Some(name) = &iclosable_name + && class.name != *name + && !imported_names.contains(name) + { + imports.push(format_type_import_projected(name, TypeKind::Interface)); + imported_names.insert(name.clone()); + imported_names.insert(format!("IID_{name}")); } // IID consts(private, for class-internal use) @@ -800,12 +864,8 @@ pub fn project_class( merge_overload_names(&mut members); // IClosable → close() (import already registered pre-emptively above) - if class - .required_interfaces - .iter() - .any(|ri| ri.iid == ICLOSABLE_IID) - { - members.push(ProjectedMember::Close); + if let Some(interface_name) = iclosable_name { + members.push(ProjectedMember::Close { interface_name }); } // IStringable → toString, toPrimitive, toStringTag @@ -878,19 +938,41 @@ pub fn project_class( // Required interface inline wrappers let mut required_ifaces = Vec::new(); - // Track names already on the main class to avoid conflicts + // Non-method members reserve their plain names. Methods are deduplicated + // by signature so overloads contributed by required interfaces survive. let mut main_member_names: HashSet = members .iter() .filter_map(|m| match m { - ProjectedMember::Method(pm) => Some(pm.name.clone()), + ProjectedMember::Method(_) => None, ProjectedMember::Property(pp) => Some(pp.name.clone()), ProjectedMember::Event(pe) => Some(pe.subscribe_name.clone()), ProjectedMember::Symbol(ps) => Some(symbol_dedup_key(&ps.kind)), - ProjectedMember::Close => Some("close".into()), + ProjectedMember::Close { .. } => Some("close".into()), ProjectedMember::AsCast => Some("as".into()), _ => None, }) .collect(); + let method_signature = |method: &ProjectedMethod| { + format!( + "{}({})", + method.name, + method + .params + .iter() + .map(|param| format!("{}:{}:{}", param.name, param.ts_type, param.optional)) + .collect::>() + .join(",") + ) + }; + let mut main_method_signatures = members + .iter() + .filter_map(|member| { + let ProjectedMember::Method(method) = member else { + return None; + }; + Some(method_signature(method)) + }) + .collect::>(); for req_iface in &class.required_interfaces { if req_iface.iid.is_empty() { @@ -974,18 +1056,15 @@ pub fn project_class( ProjectedMember::Property(pp) => pp.name.clone(), ProjectedMember::Event(pe) => pe.subscribe_name.clone(), ProjectedMember::Symbol(ps) => symbol_dedup_key(&ps.kind), - ProjectedMember::Close => "close".into(), + ProjectedMember::Close { .. } => "close".into(), ProjectedMember::AsCast => "as".into(), _ => continue, }; - // For methods: allow same name (overloads), dedup by name+param count. - // Also check plain name to prevent duplicating Symbol-based members (e.g. toString). if let ProjectedMember::Method(pm) = member { if main_member_names.contains(&name) { - continue; // already exists as a Symbol or other member + continue; } - let sig_key = format!("{}#{}", name, pm.params.len()); - if main_member_names.insert(sig_key) { + if main_method_signatures.insert(method_signature(pm)) { members.push(member.clone()); } } else if main_member_names.insert(name) { @@ -1198,7 +1277,9 @@ pub fn project_interface( // Static create() for IVector / IMap project_collection_create(iface, known_types, &mut members, &mut imports); - if iface.name == "IElementFactory" { + if iface.namespace == "Microsoft.UI.Xaml" + && super::metadata_type_name(&iface.namespace, &iface.name) == "IElementFactory" + { imports[0].symbols.push("DynWinRtElementFactory".into()); members.push(ProjectedMember::Method(ProjectedMethod { name: "create".into(), @@ -1366,12 +1447,19 @@ pub fn project_delegate( let callback_type = delegate_sigs.get(&iface.name).cloned(); + let mut runtime_symbols = vec!["DynWinRtType".into(), "WinGuid".into()]; + if callback_type + .as_deref() + .is_some_and(|callback| callback.contains("DynWinRtValue")) + { + runtime_symbols.push("DynWinRtValue".into()); + } let mut imports = vec![ProjectedImport { - symbols: vec!["DynWinRtType".into(), "WinGuid".into()], + symbols: runtime_symbols, from: get_import_name(), runtime_only: false, dts_only: false, - is_runtime_package: false, + is_runtime_package: true, }]; if let Some(ref_types) = delegate_sig_refs.get(&iface.name) { for rt in ref_types { @@ -1484,8 +1572,13 @@ fn collect_runtime_delegate_names_from_methods( TypeMeta::Interface { name, .. } if known_delegate_names.contains(name) => { delegate_names.insert(name.clone()); } - TypeMeta::Parameterized { name, args, .. } => { - let concrete = crate::meta::make_parameterized_name(name, args); + TypeMeta::Parameterized { + namespace, + name, + piid, + args, + } => { + let concrete = super::projected_parameterized_name(namespace, name, piid, args); if known_delegate_names.contains(&concrete) { delegate_names.insert(concrete); } @@ -1542,8 +1635,13 @@ fn collect_known_delegate_names_from_type( collect_known_delegate_names_from_type(result, known_delegate_names, delegate_names); collect_known_delegate_names_from_type(progress, known_delegate_names, delegate_names); } - TypeMeta::Parameterized { name, args, .. } => { - let concrete = crate::meta::make_parameterized_name(name, args); + TypeMeta::Parameterized { + namespace, + name, + piid, + args, + } => { + let concrete = super::projected_parameterized_name(namespace, name, piid, args); if known_delegate_names.contains(&concrete) { delegate_names.insert(concrete); } diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/javascript/render/declarations.rs b/tools/dynwinrt-codegen/src/codegen/winrt/javascript/render/declarations.rs index 27edbcee..8d96b34d 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/javascript/render/declarations.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/javascript/render/declarations.rs @@ -536,7 +536,7 @@ fn render_member_dts(out: &mut String, member: &ProjectedMember) { out.push_str(" /** Cast this object to another WinRT interface. */\n"); out.push_str(" as(InterfaceClass: { from(obj: any): T }): T;\n"); } - ProjectedMember::Close => { + ProjectedMember::Close { .. } => { out.push_str(" /** Release underlying WinRT resources (IClosable). */\n"); out.push_str(" close(): void;\n"); } diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/javascript/render/javascript/commonjs.rs b/tools/dynwinrt-codegen/src/codegen/winrt/javascript/render/javascript/commonjs.rs index fbae8ca0..1ea4b726 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/javascript/render/javascript/commonjs.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/javascript/render/javascript/commonjs.rs @@ -50,7 +50,7 @@ pub(super) fn convert_to_cjs_with_lazy( // `--import-name ./runtime.js` overrides. if runtime_sources.contains(&source) { runtime_imports.push((symbols, source)); - } else if !source.starts_with("./") { + } else if !source.starts_with("./") && !source.starts_with("../") { runtime_imports.push((symbols, source)); } else { let module = source @@ -218,7 +218,9 @@ pub(crate) fn convert_to_cjs_with_eager( continue; } if let Some((symbols, source)) = parse_import_line(trimmed) { - if runtime_sources.contains(&source) || !source.starts_with("./") { + if runtime_sources.contains(&source) + || (!source.starts_with("./") && !source.starts_with("../")) + { imports.push((symbols, source)); } else { if !relative_symbols.contains_key(&source) { @@ -277,7 +279,7 @@ pub(crate) fn convert_to_cjs_with_eager( #[cfg(test)] mod tests { - use super::{convert_to_cjs_with_eager, convert_to_cjs_with_lazy}; + use super::{convert_to_cjs_with_eager, convert_to_cjs_with_lazy, sanitize_ident}; use std::collections::HashSet; #[test] @@ -329,6 +331,18 @@ export class Thing extends IThing4 {\n\ assert!(cjs.contains("exports.Thing = Thing;")); assert!(!cjs.contains("__get_IThing4")); } + + #[test] + fn namespace_paths_get_distinct_loader_identifiers() { + let segmented = sanitize_ident("../../microsoft/ui/drag/drop/Widget"); + let kebab = sanitize_ident("../../microsoft/ui/drag-drop/Widget"); + + assert_ne!(segmented, kebab); + assert_eq!( + segmented, + sanitize_ident("../../microsoft/ui/drag/drop/Widget") + ); + } } /// Parse `import { A, B } from 'source';` (single-line). Returns Some(symbols, source) @@ -367,7 +381,8 @@ fn parse_import_line(line: &str) -> Option<(Vec, String)> { /// Turn a module basename into a valid JS identifier stem. WinRT type names use /// only [A-Za-z0-9_], so this is defensive against any future codegen additions. fn sanitize_ident(name: &str) -> String { - name.chars() + let sanitized = name + .chars() .map(|c| { if c.is_ascii_alphanumeric() || c == '_' { c @@ -375,7 +390,15 @@ fn sanitize_ident(name: &str) -> String { '_' } }) - .collect() + .collect::(); + if sanitized == name { + sanitized + } else { + let hash = name.as_bytes().iter().fold(0x811c9dc5u32, |hash, byte| { + (hash ^ u32::from(*byte)).wrapping_mul(0x01000193) + }); + format!("{sanitized}_{hash:08x}") + } } fn dedupe_preserving_order(v: &[String]) -> Vec { diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/javascript/render/javascript/mod.rs b/tools/dynwinrt-codegen/src/codegen/winrt/javascript/render/javascript/mod.rs index a7658161..07f95436 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/javascript/render/javascript/mod.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/javascript/render/javascript/mod.rs @@ -226,7 +226,7 @@ fn render_class_js(out: &mut String, class: &ProjectedClass) { crate::codegen::winrt::javascript::project::symbol_dedup_key(&s.kind), 0, )), - ProjectedMember::Close => Some(("close".into(), 0)), + ProjectedMember::Close { .. } => Some(("close".into(), 0)), ProjectedMember::AsCast => Some(("as".into(), 0)), ProjectedMember::Property(p) => Some((p.name.clone(), 0)), _ => None, @@ -548,7 +548,10 @@ fn render_member_js(out: &mut String, member: &ProjectedMember, _class_name: &st ProjectedMember::Symbol(symbol) => { match &symbol.kind { SymbolKind::ToString { iface_name } => { - out.push_str(&format!(" toString() {{\n return {}.from(this._obj).toString();\n }}\n", iface_name)); + out.push_str(&format!( + " toString() {{\n return {}.from(this._obj).toString();\n }}\n", + ref_marker(iface_name) + )); } SymbolKind::ToPrimitive => { out.push_str(" [Symbol.toPrimitive](_hint) {\n return this.toString();\n }\n"); @@ -626,13 +629,11 @@ fn render_member_js(out: &mut String, member: &ProjectedMember, _class_name: &st out.push_str(" return InterfaceClass.from(this._obj);\n"); out.push_str(" }\n"); } - ProjectedMember::Close => { - // Use ref_marker so the resolver picks bare `IClosable` (inline - // same-file) or `(__get_IClosable())` (lazy sibling). + ProjectedMember::Close { interface_name } => { out.push_str(" close() {\n"); out.push_str(&format!( " {}.from(this._obj).close();\n", - ref_marker("IClosable") + ref_marker(interface_name) )); out.push_str(" }\n"); } diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/javascript/signature.rs b/tools/dynwinrt-codegen/src/codegen/winrt/javascript/signature.rs index 0e74986b..2db8450a 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/javascript/signature.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/javascript/signature.rs @@ -101,7 +101,11 @@ pub(crate) fn ts_dynwinrt_type(typ: &TypeMeta) -> String { name, default_interface, } => { - let full_name = format!("{}.{}", namespace, name); + let full_name = format!( + "{}.{}", + namespace, + super::metadata_type_name(namespace, name) + ); match default_interface.as_deref() { Some(default) => format!( "DynWinRtType.runtimeClass('{}', {})", @@ -168,7 +172,11 @@ pub(crate) fn ts_dynwinrt_type(typ: &TypeMeta) -> String { members, .. } => { - let full_name = format!("{}.{}", namespace, name); + let full_name = format!( + "{}.{}", + namespace, + super::metadata_type_name(namespace, name) + ); if members.is_empty() { format!("DynWinRtType.enumType('{}')", full_name) } else { @@ -597,8 +605,13 @@ pub(crate) fn convert_array_return( arr_expr, r ) } - TypeMeta::Parameterized { name, args, .. } => { - let concrete = crate::meta::make_parameterized_name(name, args); + TypeMeta::Parameterized { + namespace, + name, + piid, + args, + } => { + let concrete = super::projected_parameterized_name(namespace, name, piid, args); if known_types.contains(&concrete) { let r = resolve_type_name(&concrete, deferred); format!( @@ -651,10 +664,15 @@ pub(crate) fn convert_return( Some(TypeMeta::F32 | TypeMeta::F64) => format!("{}.toF64()", expr), Some(TypeMeta::Bool) => format!("{}.toBool()", expr), Some(TypeMeta::Enum { .. }) => format!("{}.toNumber()", expr), - Some(typ @ TypeMeta::Parameterized { name, args, .. }) - if ireference_inner_type(typ).is_some() => - { - let concrete = crate::meta::make_parameterized_name(name, args); + Some( + typ @ TypeMeta::Parameterized { + namespace, + name, + piid, + args, + }, + ) if ireference_inner_type(typ).is_some() => { + let concrete = super::projected_parameterized_name(namespace, name, piid, args); let wrapper = resolve_type_name(&concrete, deferred); unwrap_nullable_reference_return(expr, &wrapper) } @@ -669,8 +687,13 @@ pub(crate) fn convert_return( let r = resolve_type_name(name, deferred); wrap_nullable_interface_return(expr, &r) } - Some(TypeMeta::Parameterized { name, args, .. }) => { - let concrete = crate::meta::make_parameterized_name(name, args); + Some(TypeMeta::Parameterized { + namespace, + name, + piid, + args, + }) => { + let concrete = super::projected_parameterized_name(namespace, name, piid, args); if known_types.contains(&concrete) { let r = resolve_type_name(&concrete, deferred); wrap_nullable_interface_return(expr, &r) diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/javascript/structs.rs b/tools/dynwinrt-codegen/src/codegen/winrt/javascript/structs.rs index 5fed7b8c..6ce4448b 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/javascript/structs.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/javascript/structs.rs @@ -15,10 +15,16 @@ use super::signature::{ref_marker, wrap_arg}; /// Map a struct field type to its TypeScript type annotation. pub(crate) fn ts_struct_field_type(typ: &TypeMeta) -> String { if let Some(inner) = ireference_inner_type(typ) { - let TypeMeta::Parameterized { name, args, .. } = typ else { + let TypeMeta::Parameterized { + namespace, + name, + piid, + args, + } = typ + else { unreachable!() }; - let wrapper = crate::meta::make_parameterized_name(name, args); + let wrapper = super::projected_parameterized_name(namespace, name, piid, args); return format!("{} | null | {}", ts_ireference_inner_type(inner), wrapper); } @@ -57,10 +63,18 @@ fn ts_struct_field_read_type(typ: &TypeMeta) -> String { /// Generate a `DynWinRtStruct.getXxx(index)` expression for a struct field. pub(crate) fn struct_field_getter(typ: &TypeMeta, index: usize) -> String { if ireference_inner_type(typ).is_some() { - let TypeMeta::Parameterized { name, args, .. } = typ else { + let TypeMeta::Parameterized { + namespace, + name, + piid, + args, + } = typ + else { unreachable!() }; - let wrapper = ref_marker(&crate::meta::make_parameterized_name(name, args)); + let wrapper = ref_marker(&super::projected_parameterized_name( + namespace, name, piid, args, + )); return format!( "((value) => value.isNull() ? null : new {}(value).value)(s.getObject({}))", wrapper, index diff --git a/tools/dynwinrt-codegen/src/main.rs b/tools/dynwinrt-codegen/src/main.rs index e5d02691..09a5f971 100644 --- a/tools/dynwinrt-codegen/src/main.rs +++ b/tools/dynwinrt-codegen/src/main.rs @@ -3,12 +3,16 @@ use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; use std::fs; +use std::hash::{BuildHasher, Hash, Hasher}; use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::time::{SystemTime, UNIX_EPOCH}; use clap::{Parser, Subcommand}; use serde::{Deserialize, Serialize}; use dynwinrt_codegen::codegen::com; +use dynwinrt_codegen::codegen::javascript; use dynwinrt_codegen::codegen::package; use dynwinrt_codegen::codegen::python; use dynwinrt_codegen::codegen::typescript; @@ -130,7 +134,8 @@ enum Commands { #[arg(long, default_value = "js", value_parser = ["js", "py"])] lang: String, - /// Output directory for generated files + /// Dedicated codegen-owned output directory. + /// Existing contents may be replaced or removed; do not store handwritten files here. #[arg(long, default_value = "./generated", value_name = "DIR")] output: String, @@ -287,21 +292,35 @@ fn run() -> Result<(), String> { if !dir_path.is_dir() { return Err(format!("--folder path is not a directory: {}", dir)); } - if let Ok(entries) = fs::read_dir(dir_path) { - for entry in entries.flatten() { - let path = entry.path(); - if path - .extension() + let entries = fs::read_dir(dir_path) + .map_err(|error| format!("Failed to read --folder '{}': {error}", dir))?; + let mut folder_paths = entries + .map(|entry| { + entry + .map(|entry| entry.path()) + .map_err(|error| format!("Failed to read --folder entry: {error}")) + }) + .collect::, String>>()? + .into_iter() + .filter(|path| { + path.extension() .map_or(false, |ext| ext.eq_ignore_ascii_case("winmd")) - { - eprintln!("Loading winmd from folder: {}", path.display()); - winmd_parts.push(path.to_string_lossy().to_string()); - } - } - } - if winmd_parts.is_empty() { + }) + .collect::>(); + folder_paths.sort_by(|left, right| { + let left = left.to_string_lossy(); + let right = right.to_string_lossy(); + left.to_ascii_lowercase() + .cmp(&right.to_ascii_lowercase()) + .then_with(|| left.cmp(&right)) + }); + if folder_paths.is_empty() { return Err(format!("No .winmd files found in folder: {}", dir)); } + for path in folder_paths { + eprintln!("Loading winmd from folder: {}", path.display()); + winmd_parts.push(path.to_string_lossy().to_string()); + } } if let Some(ref w) = winmd { @@ -371,13 +390,26 @@ fn run() -> Result<(), String> { // Load built-in docs as fallback (sibling .xml takes priority). doc_table.load_builtin_docs(); + if output.trim().is_empty() { + return Err("JavaScript/Python output directory cannot be empty.".into()); + } let final_output_dir = Path::new(&output); - let mut python_output = if lang == "py" && !dry_run { - Some(PythonOutputTransaction::begin(final_output_dir)?) - } else { - None - }; - let effective_output_dir = python_output + let output_contains_cwd = output_contains_current_directory(final_output_dir)?; + if matches!(lang.as_str(), "js" | "py") && !dry_run && output_contains_cwd { + return Err(format!( + "Generated output directory '{}' contains the current working directory. \ + Choose a dedicated child or sibling output directory so generation can be \ + committed atomically.", + final_output_dir.display() + )); + } + let mut output_transaction = + if matches!(lang.as_str(), "js" | "py") && !dry_run && !output_contains_cwd { + Some(OutputTransaction::begin(final_output_dir)?) + } else { + None + }; + let effective_output_dir = output_transaction .as_ref() .map(|transaction| transaction.stage_dir().to_path_buf()) .unwrap_or_else(|| final_output_dir.to_path_buf()); @@ -402,6 +434,7 @@ fn run() -> Result<(), String> { // First: partition into WinRT classes and classic-COM interfaces. let mut classes = Vec::new(); + let mut requested_winrt_interfaces = Vec::new(); let mut com_interfaces: Vec = Vec::new(); let mut com_coclasses: Vec = Vec::new(); for (ns, cls) in &class_requests { @@ -415,19 +448,23 @@ fn run() -> Result<(), String> { com_interfaces.push(com_iface); continue; } - // The type exists as an interface but is IInspectable-rooted and - // not `*Interop` — it's a plain WinRT interface. Those still need - // to go through the WinRT projection pipeline via `parse_class`, - // which will find it if it's the projected surface of a runtime - // class. If not, give a targeted error rather than the misleading - // "Class not found". - if meta::parse_class(&winmd, ns, cls).is_none() { + // Public IInspectable-rooted interfaces use the WinRT projection + // pipeline directly. `parse_class` intentionally accepts a raw + // TypeDef and cannot distinguish this case on its own. + let is_runtime_class = meta::parse_namespace(&winmd, ns) + .iter() + .any(|class| class.name == cls.as_str()); + if !is_runtime_class { + if let Some(interface) = meta::parse_interfaces(&winmd, ns) + .into_iter() + .find(|interface| interface.name == cls.as_str()) + { + requested_winrt_interfaces.push(interface); + continue; + } return Err(format!( - "{}.{} is an IInspectable-rooted WinRT interface, not a runtime class \ - or classic-COM interface. `--class-name` expects a WinRT runtime class, \ - an IUnknown-rooted classic COM interface, or a `*Interop` bridge. \ - If you meant to project a WinRT interface directly, use the full \ - namespace-projection mode (no `--class-name`).", + "{}.{} is an exclusive IInspectable interface, not a public runtime \ + class or standalone WinRT interface.", ns, cls )); } @@ -436,6 +473,13 @@ fn run() -> Result<(), String> { com_coclasses.push(coclass); continue; } + if let Some(interface) = meta::parse_interfaces(&winmd, ns) + .into_iter() + .find(|interface| interface.name == cls.as_str()) + { + requested_winrt_interfaces.push(interface); + continue; + } match meta::parse_class(&winmd, ns, cls) { Some(mut c) => { doc_table.apply_to_class(&mut c); @@ -553,17 +597,16 @@ fn run() -> Result<(), String> { } if !dry_run { - fs::create_dir_all(&com_output_dir).map_err(|e| { - format!( - "Failed to create COM output directory '{}': {}", - com_output_dir.display(), - e - ) - })?; + ensure_safe_generated_parent( + output_dir, + &com_output_dir.join(".dynwinrt-write-check"), + )?; let manifest_update = prepare_com_generation_manifest(&com_output_dir, &root_files)?; for (file_name, content) in &planned_files { - fs::write(com_output_dir.join(file_name), content) + let path = com_output_dir.join(file_name); + ensure_safe_generated_destination(output_dir, &path)?; + fs::write(&path, content) .map_err(|e| format!("Failed to write {}: {}", file_name, e))?; } apply_com_generation_manifest(&com_output_dir, manifest_update)?; @@ -584,16 +627,19 @@ fn run() -> Result<(), String> { write_com_js_barrel(&com_output_dir)?; } - if classes.is_empty() { + if classes.is_empty() && requested_winrt_interfaces.is_empty() { if !dry_run { finalize_com_generation(output_dir)?; } + if let Some(transaction) = output_transaction.take() { + transaction.commit()?; + } return Ok(()); } } winui::add_implicit_classes(&winmd, &mut classes); - let mut implicit_interfaces = Vec::new(); + let mut implicit_interfaces = requested_winrt_interfaces; winui::add_implicit_interfaces(&winmd, &classes, &mut implicit_interfaces); let existing_python_identities = if lang == "py" && !dry_run { read_python_type_inventory(output_dir)? @@ -870,10 +916,9 @@ fn run() -> Result<(), String> { if lang == "py" && !dry_run { write_python_package_manifest(output_dir, final_output_dir)?; write_python_generated_inventory(output_dir, pyi)?; - python_output - .take() - .expect("Python output transaction must exist") - .commit()?; + } + if let Some(transaction) = output_transaction.take() { + transaction.commit()?; } } } @@ -901,9 +946,17 @@ fn generate_for_types( all_classes.extend(deps.classes); all_interfaces.extend(deps.interfaces); all_enums.extend(deps.enums); - if lang != "py" { - validate_unique_class_output_names(&all_classes)?; - } + let previous_javascript_inventory = if lang != "py" { + if dry_run { + check_javascript_layout_inventory(output_dir)?; + } else { + ensure_javascript_layout_inventory(output_dir)?; + } + read_javascript_type_inventory(output_dir)? + } else { + JavaScriptTypeInventory::default() + }; + let previous_javascript_records = previous_javascript_inventory.records; // Newly-merged dependency types haven't been doc-annotated yet. Apply doc table // uniformly so dependency classes/interfaces/enums carry the same XML docs as @@ -917,6 +970,59 @@ fn generate_for_types( for e in all_enums.iter_mut() { doc_table.apply_to_enum(e); } + let current_javascript_records = if lang != "py" { + javascript_type_layout_records(&all_classes, &all_interfaces, &all_enums)? + } else { + Vec::new() + }; + let mut retained_javascript_renames = Vec::new(); + let _javascript_layout = if lang != "py" { + validate_javascript_type_layout_records( + &previous_javascript_records, + ¤t_javascript_records, + )?; + let identities = previous_javascript_records + .iter() + .chain(current_javascript_records.iter()) + .map(|record| record.identity.clone()); + let layout = javascript::install_javascript_module_layout_with_records( + identities, + previous_javascript_records.iter().cloned(), + )?; + let projected_names = javascript::javascript_output_targets() + .into_iter() + .map(|target| (target.identity, target.projected_name)) + .collect::>(); + let current_identities = current_javascript_records + .iter() + .map(|record| record.identity.clone()) + .collect::>(); + retained_javascript_renames = previous_javascript_records + .iter() + .filter(|record| { + projected_names + .get(&record.identity) + .is_some_and(|projected| projected != &record.projected_name) + && !current_identities.contains(&record.identity) + }) + .cloned() + .collect::>(); + let current_struct_helpers = + javascript::validate_struct_helper_identities(&all_classes, &all_interfaces)?; + validate_generated_struct_helper_identities_against(output_dir, ¤t_struct_helpers)?; + if !output_dir.join(JAVASCRIPT_TYPE_INVENTORY).is_file() { + ensure_uninventoried_javascript_targets_absent(output_dir)?; + } + javascript::apply_javascript_projected_names( + &mut all_classes, + &mut all_interfaces, + &mut all_enums, + ); + validate_unique_class_output_names(&all_classes)?; + Some(layout) + } else { + None + }; // Compute the set of interfaces `generate_js_files` will actually emit // (matches the class-name-collision + no-IID filter there). Everything @@ -966,6 +1072,15 @@ fn generate_for_types( } } } + if lang != "py" { + for target in javascript::javascript_output_targets() { + known_types.insert(target.projected_name); + known_types.insert(format!( + "{}.{}", + target.identity.namespace, target.identity.name + )); + } + } let delegate_type_names: HashSet = all_interfaces .iter() @@ -979,7 +1094,7 @@ fn generate_for_types( let mut req_iface_count: HashMap = HashMap::new(); for class in &all_classes { for ri in &class.required_interfaces { - if ri.iid.is_empty() { + if ri.iid.is_empty() || ri.generic_piid.is_some() { continue; } req_iface_count @@ -988,11 +1103,26 @@ fn generate_for_types( .or_insert((ri, 1)); } } - let shared_iids: HashSet = req_iface_count + let mut shared_iids: HashSet = req_iface_count .iter() .filter(|(_, (_, count))| *count >= 2) .map(|(iid, _)| iid.clone()) .collect(); + if lang != "py" { + shared_iids.extend( + all_interfaces + .iter() + .filter(|interface| interface.generic_piid.is_none()) + .map(|interface| interface.iid.clone()), + ); + shared_iids.extend(previous_javascript_records.iter().filter_map(|record| { + (record.identity.kind == javascript::JavaScriptTypeKind::Interface + && record.abi_identity.starts_with("iid:")) + .then(|| record.abi_identity.strip_prefix("iid:")) + .flatten() + .map(str::to_string) + })); + } let shared_interfaces: Vec = req_iface_count .iter() @@ -1063,6 +1193,16 @@ fn generate_for_types( &delegate_sig_refs, &delegate_param_wraps, )?; + write_retained_javascript_projected_aliases(output_dir, &retained_javascript_renames)?; + validate_generated_struct_helper_identities(output_dir)?; + write_javascript_type_inventory( + output_dir, + &emitted_javascript_type_records( + output_dir, + &previous_javascript_records, + ¤t_javascript_records, + )?, + )?; } drop(python_layout); } @@ -1126,2542 +1266,4663 @@ fn install_python_generation_layout( python::install_python_module_layout(identities) } -fn validate_unique_class_output_names(classes: &[meta::ClassMeta]) -> Result<(), String> { - let mut full_name_by_short_name: HashMap<&str, &str> = HashMap::new(); - for class in classes { - match full_name_by_short_name.get(class.name.as_str()) { - Some(existing) if *existing != class.full_name => { - return Err(format!( - "Cannot generate `{}` and `{}` in one output directory because both use \ - the short class name `{}`. Generate them separately or select only one type.", - existing, class.full_name, class.name - )); - } - Some(_) => {} - None => { - full_name_by_short_name.insert(&class.name, &class.full_name); - } - } - } - Ok(()) -} - -fn generate_js_files( - output_dir: &Path, - all_classes: &[meta::ClassMeta], - all_interfaces: &[meta::InterfaceMeta], - all_enums: &[TypeMeta], - shared_interfaces: &[meta::InterfaceMeta], - known_types: &HashSet, - delegate_type_names: &HashSet, - shared_iids: &HashSet, - delegate_sigs: &HashMap, - delegate_sig_refs: &HashMap>, - delegate_param_wraps: &HashMap>, -) -> Result<(), String> { - let emit = |name: &str, js_code: &str, dts_code: &str| -> Result<(), String> { - let js_path = output_dir.join(format!("{}.js", name)); - let dts_path = output_dir.join(format!("{}.d.ts", name)); - write_file(&js_path, js_code)?; - write_file(&dts_path, dts_code)?; - println!("Generated {}", js_path.display()); - Ok(()) - }; +const JAVASCRIPT_TYPE_INVENTORY: &str = ".dynwinrt-js-types"; +const JAVASCRIPT_TYPE_INVENTORY_VERSION: u32 = 1; - // Interfaces whose short name collides with a class in this batch would - // overwrite the class's UIElement.js / Button.js etc. Skip them; the - // parameterized instantiations that produce these entries are not - // themselves useful runtime bindings. - let class_names: HashSet<&str> = all_classes.iter().map(|c| c.name.as_str()).collect(); +#[derive(Debug, Default, Deserialize, Serialize)] +struct JavaScriptTypeInventory { + version: u32, + records: Vec, +} - // Interface entries with no IID and no generic PIID are synthesized stubs - // (typically parameterized instantiations named after a class type - // parameter, e.g. `UIElement` from `IIterable`). They must not - // be emitted — the file would have a broken `registerInterface` call with - // no matching IID declaration and would overwrite any real class file of - // the same name. - fn is_emittable_interface(iface: &meta::InterfaceMeta) -> bool { - !iface.iid.is_empty() +fn ensure_javascript_layout_inventory(output_dir: &Path) -> Result<(), String> { + if !output_dir.is_dir() { + return Ok(()); } + check_javascript_layout_inventory(output_dir) +} - for iface in shared_interfaces { - if class_names.contains(iface.name.as_str()) { - continue; - } - if !is_emittable_interface(iface) { - continue; - } - let projected = project::project_interface( - iface, - known_types, - delegate_type_names, - delegate_sigs, - delegate_sig_refs, - delegate_param_wraps, - ); - let js = render_js::render(&projected); - let dts = render_dts::render(&projected); - emit(&iface.name, &js, &dts)?; +fn check_javascript_layout_inventory(output_dir: &Path) -> Result<(), String> { + if !output_dir.is_dir() { + return Ok(()); } - for iface in all_interfaces { - if class_names.contains(iface.name.as_str()) { - continue; - } - if !is_emittable_interface(iface) { - continue; - } - let projected = project::project_interface( - iface, - known_types, - delegate_type_names, - delegate_sigs, - delegate_sig_refs, - delegate_param_wraps, - ); - let js = render_js::render(&projected); - let dts = render_dts::render(&projected); - emit(&iface.name, &js, &dts)?; + if output_dir.join(JAVASCRIPT_TYPE_INVENTORY).is_file() { + return Ok(()); } - for en in all_enums { - if let TypeMeta::Enum { name, .. } = en { - if name.contains('<') { + fn contains_generated_implementation(root: &Path, current: &Path) -> bool { + let Ok(entries) = fs::read_dir(current) else { + return false; + }; + for entry in entries.flatten() { + let path = entry.path(); + let Ok(metadata) = fs::symlink_metadata(&path) else { continue; - } // skip CLR projection types - if class_names.contains(name.as_str()) { + }; + if is_link_or_reparse_point(&metadata) { continue; } - if let Some(projected) = project::project_enum(en) { - let js = render_js::render(&projected); - let dts = render_dts::render(&projected); - emit(name, &js, &dts)?; + if metadata.is_dir() { + if current == root && path.file_name().is_some_and(|name| name == "com") { + continue; + } + if contains_generated_implementation(root, &path) { + return true; + } + continue; + } + let Some(name) = path.file_name().and_then(|name| name.to_str()) else { + continue; + }; + if matches!( + name, + "index.js" + | "index.mjs" + | "index.d.ts" + | "index.proxy.js" + | "index.getter.js" + | "lifetime.js" + | "lifetime.d.ts" + | "package.json" + ) { + continue; + } + if (name.ends_with(".js") || name.ends_with(".d.ts")) + && fs::read_to_string(&path) + .map(|content| content.starts_with("// Generated by dynwinrt-codegen")) + .unwrap_or(false) + { + return true; } } + false } - // First pass: emit "real" classes. A class is emit-worthy if any of these - // hold: - // * it has a default interface with a resolvable IID (normal - // activatable / composable class), OR - // * it has factory/statics interfaces (statics-only utility classes such - // as `LimitedAccessFeatures`, `AICapabilities`, `PowerManager`), OR - // * it has required or overridable methods callable on an inbound obj. - // - // Only synthetic parameterized "instantiations" (e.g. `IIterable` - // reprojected as a class stub) with nothing at all fall through to the - // stub-emission pass below. - let mut emitted_class_names: HashSet = HashSet::new(); - let class_is_usable = |class: &meta::ClassMeta| -> bool { - let has_default_iid = class - .default_interface - .as_ref() - .map_or(false, |di| !di.iid.is_empty()); - let has_statics_or_factory = - !class.static_interfaces.is_empty() || !class.factory_interfaces.is_empty(); - let has_required = !class.required_interfaces.is_empty(); - has_default_iid || has_statics_or_factory || has_required - }; - for class in all_classes { - if !class_is_usable(class) { - continue; - } - let projected = project::project_class( - class, - known_types, - delegate_type_names, - shared_iids, - delegate_sigs, - delegate_sig_refs, - delegate_param_wraps, - ); - let js = render_js::render(&projected); - let dts = render_dts::render(&projected); - emit(&class.name, &js, &dts)?; - emitted_class_names.insert(class.name.clone()); - } - // Second pass: emit stubs for genuinely empty class shells (parameterized - // synthetics from the projection layer that carry no methods). Stubs keep - // ESM barrel imports linkable even when the underlying type isn't - // constructible at runtime. - for class in all_classes { - if class_is_usable(class) { - continue; - } - if emitted_class_names.contains(&class.name) { - continue; - } - let stub_js = format!( - "// Generated by dynwinrt-codegen \u{2014} do not edit\n\ - // Placeholder for a class whose default interface has no IID in\n\ - // the loaded winmd graph. Any attempt to use it will throw.\n\ - const __unavailable = () => {{ throw new Error(\"'{name}' has no default interface in the loaded winmd graph and cannot be constructed. Add its owning package to `additionalWinmds` / `additionalRefs`.\"); }};\n\ - class {name} {{ constructor() {{ __unavailable(); }} }}\n\ - exports.{name} = {name};\n", - name = class.name, - ); - let stub_dts = format!( - "// Generated by dynwinrt-codegen \u{2014} do not edit\n\ - // Placeholder: throwing at construction. Typed as a class so - // other .d.ts files can still use `{name}` as a parameter / - // return type.\n\ - export declare class {name} {{ private constructor(); }}\n", - name = class.name, - ); - emit(&class.name, &stub_js, &stub_dts)?; - emitted_class_names.insert(class.name.clone()); + + if contains_generated_implementation(output_dir, output_dir) { + return Err(format!( + "Existing JavaScript bindings in '{}' use the legacy flat layout and cannot be \ + updated incrementally without type identities. Remove that generated directory \ + and regenerate it once to migrate to the namespace layout.", + output_dir.display() + )); } + Ok(()) +} - // Post-process: strip imports that reference non-existent sibling files. - // This handles cases where a class pulls in a type reference (e.g. WinUI XAML - // classes referencing Microsoft.UI.Composition types whose winmd was removed - // in later Windows App SDK versions) but the target file was never emitted. - // Rather than leave the entire binding set broken at load time, we drop the - // import — any methods that depended on that type will surface as runtime - // ReferenceErrors when actually called, but the module loads. - strip_broken_imports(output_dir)?; +#[cfg(test)] +fn javascript_type_identities( + classes: &[meta::ClassMeta], + interfaces: &[meta::InterfaceMeta], + enums: &[TypeMeta], +) -> Result, String> { + Ok(javascript_type_layout_records(classes, interfaces, enums)? + .into_iter() + .map(|record| record.identity) + .collect()) +} - Ok(()) +fn javascript_interface_abi_identity(interface: &meta::InterfaceMeta) -> String { + javascript::interface_abi_identity(interface) } -/// Write the four barrel entries plus `package.json` alongside the per-type -/// files already emitted into `output_dir`. -/// -/// The four barrels are: -/// * `index.js` — CJS `Object.defineProperty` getter barrel — real -/// values, lazy, default for `require('@winapp/bindings')`. -/// * `index.mjs` — standard ESM re-export barrel — real values, -/// tree-shakable for bundlers. -/// * `index.proxy.js` — legacy CJS Proxy barrel — lexer-visible -/// `exports.X = ...` assignments for opt-in -/// compatibility via `@winapp/bindings/proxy`. -/// * `index.d.ts` — TypeScript declarations shared across every path. -/// -/// After the barrels are on disk we run `strip_broken_imports` so any lazy -/// getters referencing sibling modules that were filtered out during emission -/// are removed cleanly. Then we scan the directory for real `.js` files (each -/// one corresponds to a subpath consumer can deep-import) and emit a -/// `package.json` with the conditional-exports map. -fn write_js_barrel_and_manifest(output_dir: &Path, index_content: &str) -> Result<(), String> { - let js_path = output_dir.join("index.js"); - let mjs_path = output_dir.join("index.mjs"); - let proxy_path = output_dir.join("index.proxy.js"); - let dts_path = output_dir.join("index.d.ts"); - let _ = index_content; - write_lifetime_module(output_dir)?; - - // Clean up any stale `.index.ts` cache from older codegen versions. - let stale = output_dir.join(".index.ts"); - if stale.exists() { - let _ = fs::remove_file(&stale); +fn javascript_type_layout_records( + classes: &[meta::ClassMeta], + interfaces: &[meta::InterfaceMeta], + enums: &[TypeMeta], +) -> Result, String> { + let record = |identity: javascript::JavaScriptTypeIdentity, abi_identity: String| { + javascript::JavaScriptTypeLayoutRecord::new( + identity.clone(), + identity.name.clone(), + abi_identity, + ) + }; + let interface_record = |interface: &meta::InterfaceMeta| { + let abi_identity = javascript_interface_abi_identity(interface); + let kind = javascript_interface_kind(interface); + let identity = if interface.generic_piid.is_some() { + javascript::JavaScriptTypeIdentity::with_variant( + &interface.namespace, + &javascript::parameterized_interface_name( + &interface.namespace, + &interface.name, + interface.generic_piid.as_deref().unwrap_or_default(), + &interface.generic_args, + ), + kind, + &javascript::parameterized_reference_identity( + interface.generic_piid.as_deref().unwrap_or_default(), + &interface.generic_args, + ), + ) + } else { + javascript::JavaScriptTypeIdentity::new(&interface.namespace, &interface.name, kind) + }; + record(identity, abi_identity) + }; + let class_identities = classes + .iter() + .map(|class| (class.namespace.as_str(), class.name.as_str())) + .collect::>(); + let mut required_iid_counts = HashMap::<&str, usize>::new(); + for interface in classes + .iter() + .flat_map(|class| class.required_interfaces.iter()) + .filter(|interface| interface.generic_piid.is_none() && !interface.iid.is_empty()) + { + *required_iid_counts + .entry(interface.iid.as_str()) + .or_default() += 1; } + let mut records = classes + .iter() + .map(|class| { + record( + javascript::JavaScriptTypeIdentity::new( + &class.namespace, + &class.name, + javascript::JavaScriptTypeKind::Class, + ), + "type".into(), + ) + }) + .collect::>(); + records.extend( + classes + .iter() + .flat_map(|class| class.required_interfaces.iter()) + .filter(|interface| { + !interface.iid.is_empty() + && interface.generic_piid.is_none() + && required_iid_counts + .get(interface.iid.as_str()) + .is_some_and(|count| *count >= 2) + && !class_identities + .contains(&(interface.namespace.as_str(), interface.name.as_str())) + }) + .map(interface_record) + .collect::>(), + ); + records.extend( + interfaces + .iter() + .filter(|interface| { + !interface.iid.is_empty() + && !class_identities + .contains(&(interface.namespace.as_str(), interface.name.as_str())) + }) + .map(interface_record) + .collect::>(), + ); + records.extend(enums.iter().filter_map(|typ| { + let TypeMeta::Enum { + namespace, name, .. + } = typ + else { + return None; + }; + (!class_identities.contains(&(namespace.as_str(), name.as_str()))).then(|| { + record( + javascript::JavaScriptTypeIdentity::new( + namespace, + name, + javascript::JavaScriptTypeKind::Enum, + ), + "type".into(), + ) + }) + })); + Ok(records) +} - // Remove the previous opt-in getter barrel name if it exists from older - // generated output. `index.js` is now the getter barrel and - // `index.proxy.js` is the explicit compatibility path. - let stale_getter = output_dir.join("index.getter.js"); - if stale_getter.exists() { - let _ = fs::remove_file(&stale_getter); +fn javascript_interface_kind(interface: &meta::InterfaceMeta) -> javascript::JavaScriptTypeKind { + if interface + .methods + .iter() + .any(|method| method.name == ".ctor") + && interface + .methods + .iter() + .any(|method| method.name == "Invoke") + { + javascript::JavaScriptTypeKind::Delegate + } else { + javascript::JavaScriptTypeKind::Interface } - - // Sweep index.js and any other files that still reference sibling modules - // that were skipped by class/interface filters during emission. - strip_broken_imports(output_dir)?; - - // Build the barrel from what actually landed on disk rather than from raw - // metadata. This avoids root ESM/CJS barrels referencing files or helper - // exports that were filtered out (for example ref-only WinUI controls such - // as CompositionTarget). - let index_content = render_index_from_existing_js_files(output_dir)?; - - let js_content = typescript::esm_index_to_cjs_getter(&index_content); - fs::write(&js_path, &js_content) - .map_err(|e| format!("Failed to write {}: {}", js_path.display(), e))?; - - let mjs_content = typescript::esm_index_to_esm(&index_content); - fs::write(&mjs_path, &mjs_content) - .map_err(|e| format!("Failed to write {}: {}", mjs_path.display(), e))?; - - let proxy_content = typescript::esm_index_to_cjs_lazy(&index_content); - fs::write(&proxy_path, &proxy_content) - .map_err(|e| format!("Failed to write {}: {}", proxy_path.display(), e))?; - - fs::write(&dts_path, &index_content) - .map_err(|e| format!("Failed to write {}: {}", dts_path.display(), e))?; - - write_bindings_manifest(output_dir)?; - - println!("Generated {}", js_path.display()); - Ok(()) } -fn prepare_com_generation_manifest( - com_output_dir: &Path, - updated_roots: &BTreeMap>, -) -> Result { - let path = com_output_dir.join(COM_MANIFEST_FILE); - let mut manifest = if path.exists() { - let content = fs::read_to_string(&path) - .map_err(|error| format!("Failed to read {}: {error}", path.display()))?; - serde_json::from_str::(&content).map_err(|error| { - format!( - "Invalid COM generation manifest {}: {error}", - path.display() - ) - })? - } else { - ComGenerationManifest { - version: 1, - roots: BTreeMap::new(), - } - }; - if manifest.version != 1 { +fn read_javascript_type_inventory(output_dir: &Path) -> Result { + if output_dir.is_dir() && !output_contains_current_directory(output_dir)? { + ensure_generated_tree_has_no_links(output_dir)?; + } + let path = output_dir.join(JAVASCRIPT_TYPE_INVENTORY); + if !path.is_file() { + return Ok(JavaScriptTypeInventory::default()); + } + let content = fs::read_to_string(&path) + .map_err(|error| format!("Failed to read {}: {error}", path.display()))?; + let inventory = serde_json::from_str::(&content).map_err(|error| { + format!( + "Invalid JavaScript type inventory {}: {error}", + path.display() + ) + })?; + if inventory.version != JAVASCRIPT_TYPE_INVENTORY_VERSION { return Err(format!( - "Unsupported COM generation manifest version {} in {}", - manifest.version, + "Unsupported or invalid JavaScript type inventory in {}", path.display() )); } + validate_javascript_type_layout_records(&inventory.records, &[])?; + validate_javascript_inventory_files(output_dir, &inventory.records)?; + Ok(inventory) +} - let previous_files = updated_roots - .keys() - .filter_map(|root| manifest.roots.get(root)) - .flatten() - .cloned() - .collect::>(); - for (root, files) in updated_roots { - manifest.roots.insert(root.clone(), files.clone()); +fn validate_javascript_inventory_files( + output_dir: &Path, + records: &[javascript::JavaScriptTypeLayoutRecord], +) -> Result<(), String> { + let _layout = javascript::install_javascript_module_layout_with_records( + records.iter().map(|record| record.identity.clone()), + records.iter().cloned(), + )?; + let targets = javascript::javascript_output_targets(); + let target_layout = targets + .iter() + .map(|target| { + ( + &target.identity, + ( + target.projected_name.as_str(), + &target.compatibility_aliases, + ), + ) + }) + .collect::>(); + if let Some(record) = records.iter().find(|record| { + target_layout + .get(&record.identity) + .is_none_or(|(projected, aliases)| { + *projected != record.projected_name || *aliases != &record.compatibility_aliases + }) + }) { + return Err(format!( + "JavaScript type inventory has non-deterministic projected name `{}` for `{}.{}`", + record.projected_name, record.identity.namespace, record.identity.name + )); } - let retained_files = manifest - .roots - .values() - .flatten() - .cloned() + let expected_canonical = targets + .iter() + .map(|target| target.canonical_module.clone()) .collect::>(); - let stale_files = previous_files - .difference(&retained_files) - .cloned() + let shared_output = output_contains_current_directory(output_dir)?; + let expected_namespace_roots = expected_canonical + .iter() + .filter_map(|module| module.split('/').next().map(str::to_string)) .collect::>(); - for stale in &stale_files { - let relative = Path::new(stale); - if relative.components().count() != 1 - || !(stale.ends_with(".js") || stale.ends_with(".d.ts")) - { + let mut actual_canonical = BTreeSet::new(); + + fn visit( + root: &Path, + current: &Path, + actual_canonical: &mut BTreeSet, + shared_output: bool, + expected_namespace_roots: &BTreeSet, + ) { + let Ok(entries) = fs::read_dir(current) else { + return; + }; + for entry in entries.flatten() { + let path = entry.path(); + if path.is_dir() { + if path == root.join("com") { + continue; + } + if shared_output + && current == root + && path + .file_name() + .and_then(|name| name.to_str()) + .is_none_or(|name| !expected_namespace_roots.contains(name)) + { + continue; + } + visit( + root, + &path, + actual_canonical, + shared_output, + expected_namespace_roots, + ); + continue; + } + let Some(name) = path.file_name().and_then(|name| name.to_str()) else { + continue; + }; + if !name.ends_with(".js") + || matches!( + name, + "index.js" | "index.proxy.js" | "index.getter.js" | "lifetime.js" + ) + { + continue; + } + let Ok(content) = fs::read_to_string(&path) else { + continue; + }; + if content.starts_with("// Generated by dynwinrt-codegen") + && let Ok(relative) = path.strip_prefix(root) + { + actual_canonical.insert( + relative + .with_extension("") + .to_string_lossy() + .replace('\\', "/"), + ); + } + } + } + visit( + output_dir, + output_dir, + &mut actual_canonical, + shared_output, + &expected_namespace_roots, + ); + + if actual_canonical != expected_canonical { + let summarize = + |values: BTreeSet| values.into_iter().take(5).collect::>().join(", "); + return Err(format!( + "JavaScript generated type inventory does not match '{}' (missing canonical: [{}]; \ + unexpected canonical: [{}])", + output_dir.display(), + summarize( + expected_canonical + .difference(&actual_canonical) + .cloned() + .collect() + ), + summarize( + actual_canonical + .difference(&expected_canonical) + .cloned() + .collect() + ), + )); + } + let records_by_identity = records + .iter() + .map(|record| (&record.identity, record)) + .collect::>(); + for target in targets { + for suffix in ["js", "d.ts"] { + let canonical = output_dir.join(format!("{}.{suffix}", target.canonical_module)); + if !canonical.is_file() { + return Err(format!( + "JavaScript generated type inventory references missing files for `{}.{}`", + target.identity.namespace, target.identity.name + )); + } + } + let record = records_by_identity[&target.identity]; + let js_path = output_dir.join(format!("{}.js", target.canonical_module)); + let js = fs::read_to_string(&js_path) + .map_err(|error| format!("Failed to read {}: {error}", js_path.display()))?; + let implementation_export = + if target.identity.kind == javascript::JavaScriptTypeKind::Delegate { + format!("exports.IID_{} =", record.implementation_name) + } else { + format!("exports.{} =", record.implementation_name) + }; + if !js.contains(&implementation_export) { return Err(format!( - "Refusing unsafe path `{stale}` in COM generation manifest {}", - path.display() + "JavaScript type inventory implementation `{}` is missing from '{}'", + record.implementation_name, + js_path.display() )); } } - Ok(ComManifestUpdate { - manifest, - stale_files, - }) + Ok(()) } -fn apply_com_generation_manifest( - com_output_dir: &Path, - update: ComManifestUpdate, +fn ensure_uninventoried_javascript_targets_absent(output_dir: &Path) -> Result<(), String> { + for target in javascript::javascript_output_targets() { + for suffix in ["js", "d.ts"] { + let path = output_dir.join(format!("{}.{suffix}", target.canonical_module)); + if path.exists() { + return Err(format!( + "Existing JavaScript canonical module '{}' has no type inventory. Remove the \ + incomplete generated output and regenerate it.", + path.display() + )); + } + } + } + Ok(()) +} + +fn validate_javascript_type_layout_records( + previous: &[javascript::JavaScriptTypeLayoutRecord], + current: &[javascript::JavaScriptTypeLayoutRecord], ) -> Result<(), String> { - let path = com_output_dir.join(COM_MANIFEST_FILE); - for stale in &update.stale_files { - let stale_path = com_output_dir.join(stale); - if stale_path.exists() { - fs::remove_file(&stale_path) - .map_err(|error| format!("Failed to remove {}: {error}", stale_path.display()))?; + let mut previous_by_identity = HashMap::new(); + for record in previous { + if previous_by_identity + .insert(record.identity.clone(), record) + .is_some() + { + return Err(format!( + "JavaScript type inventory contains duplicate layout records for `{}.{}`", + record.identity.namespace, record.identity.name + )); } } - let content = serde_json::to_string_pretty(&update.manifest) - .map_err(|error| format!("Failed to serialize COM generation manifest: {error}"))?; - fs::write(&path, format!("{content}\n")) - .map_err(|error| format!("Failed to write {}: {error}", path.display())) + + let mut abi_by_identity = previous + .iter() + .map(|record| (record.identity.clone(), record.abi_identity.as_str())) + .collect::>(); + for record in current { + if let Some(existing) = abi_by_identity.get(&record.identity) { + if *existing != record.abi_identity { + return Err(format!( + "JavaScript output identity `{}.{}` maps to multiple WinRT ABI identities \ + (`{existing}` and `{}`). Closed generic interfaces with identical generated \ + names are not supported; generation stopped before either module was overwritten.", + record.identity.namespace, record.identity.name, record.abi_identity, + )); + } + } else { + abi_by_identity.insert(record.identity.clone(), &record.abi_identity); + } + } + Ok(()) } -fn write_com_js_barrel(com_output_dir: &Path) -> Result<(), String> { - let mut modules: BTreeMap> = BTreeMap::new(); - let mut contents: BTreeMap = BTreeMap::new(); - let entries = fs::read_dir(com_output_dir).map_err(|error| { - format!( - "Failed to read COM output directory {}: {error}", - com_output_dir.display() - ) - })?; - for entry in entries.flatten() { - let path = entry.path(); - let Some(file_name) = path.file_name().and_then(|name| name.to_str()) else { - continue; - }; - let Some(module) = file_name.strip_suffix(".js") else { - continue; - }; - if module == "index" { +fn write_retained_javascript_projected_aliases( + output_dir: &Path, + renamed: &[javascript::JavaScriptTypeLayoutRecord], +) -> Result<(), String> { + let targets = javascript::javascript_output_targets() + .into_iter() + .map(|target| (target.identity.clone(), target)) + .collect::>(); + let append = |content: &mut String, line: String| { + if !content.contains(&line) { + if !content.ends_with('\n') { + content.push('\n'); + } + content.push_str(&line); + } + }; + for record in renamed { + let target = targets.get(&record.identity).ok_or_else(|| { + format!( + "JavaScript module layout does not contain renamed type `{}.{}`", + record.identity.namespace, record.identity.name + ) + })?; + if target.projected_name == record.implementation_name { continue; } - let content = fs::read_to_string(&path) - .map_err(|error| format!("Failed to read {}: {error}", path.display()))?; - let exports = collect_com_cjs_exports(&content); - if !exports.is_empty() { - modules.insert(module.to_string(), exports); - contents.insert(module.to_string(), content); + let js_path = output_dir.join(format!("{}.js", target.canonical_module)); + let dts_path = output_dir.join(format!("{}.d.ts", target.canonical_module)); + let mut js = fs::read_to_string(&js_path) + .map_err(|error| format!("Failed to read {}: {error}", js_path.display()))?; + let mut dts = fs::read_to_string(&dts_path) + .map_err(|error| format!("Failed to read {}: {error}", dts_path.display()))?; + let implementation = &record.implementation_name; + let new = &target.projected_name; + if record.identity.kind == javascript::JavaScriptTypeKind::Delegate { + if !js.contains(&format!("exports.IID_{implementation} =")) { + return Err(format!( + "Retained delegate module '{}' does not export IID_{implementation}", + js_path.display() + )); + } + append( + &mut js, + format!( + "exports.IID_{new} = exports.IID_{implementation};\n\ + exports.{new}_PARAM_TYPES = exports.{implementation}_PARAM_TYPES;\n" + ), + ); + append( + &mut dts, + format!( + "export {{ IID_{implementation} as IID_{new}, \ + {implementation}_PARAM_TYPES as {new}_PARAM_TYPES }};\n\ + export type {new} = {implementation};\n" + ), + ); + } else { + if !js.contains(&format!("exports.{implementation} =")) { + return Err(format!( + "Retained JavaScript module '{}' does not export `{implementation}`", + js_path.display() + )); + } + append( + &mut js, + format!("exports.{new} = exports.{implementation};\n"), + ); + append( + &mut dts, + format!("export {{ {implementation} as {new} }};\n"), + ); + if js.contains(&format!("exports.IID_{implementation} =")) { + append( + &mut js, + format!("exports.IID_{new} = exports.IID_{implementation};\n"), + ); + append( + &mut dts, + format!("export {{ IID_{implementation} as IID_{new} }};\n"), + ); + } } + ensure_safe_generated_destination(output_dir, &js_path)?; + ensure_safe_generated_destination(output_dir, &dts_path)?; + fs::write(&js_path, js) + .map_err(|error| format!("Failed to write {}: {error}", js_path.display()))?; + fs::write(&dts_path, dts) + .map_err(|error| format!("Failed to write {}: {error}", dts_path.display()))?; } - deduplicate_com_barrel_exports(&mut modules, &contents)?; - - let mut index = String::from("// Generated by dynwinrt-codegen - do not edit\n"); - for (module, exports) in &modules { - index.push_str(&format!( - "export {{ {} }} from './{module}.js';\n", - exports.iter().cloned().collect::>().join(", ") - )); - } - let cjs_index = typescript::esm_index_to_cjs_getter(&index); - let esm_index = typescript::esm_index_to_esm(&index); - fs::write(com_output_dir.join("index.js"), &cjs_index) - .map_err(|error| format!("Failed to write COM index.js: {error}"))?; - fs::write(com_output_dir.join("index.mjs"), &esm_index) - .map_err(|error| format!("Failed to write COM index.mjs: {error}"))?; - fs::write(com_output_dir.join("index.d.ts"), &index) - .map_err(|error| format!("Failed to write COM index.d.ts: {error}"))?; - - let package = "{\n \"type\": \"commonjs\",\n \"sideEffects\": false\n}\n"; - fs::write(com_output_dir.join("package.json"), package) - .map_err(|error| format!("Failed to write COM package boundary: {error}"))?; Ok(()) } -fn deduplicate_com_barrel_exports( - modules: &mut BTreeMap>, - contents: &BTreeMap, +fn write_javascript_type_inventory( + output_dir: &Path, + records: &[javascript::JavaScriptTypeLayoutRecord], ) -> Result<(), String> { - let mut owners = BTreeMap::)>::new(); - for (module, exports) in modules.iter_mut() { - let content = &contents[module]; - let names = exports.iter().cloned().collect::>(); - for name in names { - let signature = native_pod_factory_signature(content, &name); - if let Some((owner, owner_signature)) = owners.get(&name) { - if signature.is_some() && signature.as_ref() == owner_signature.as_ref() { - exports.remove(&name); - } else { - return Err(format!( - "COM barrel export `{name}` is ambiguous between `{owner}.js` and `{module}.js`" - )); - } + let inventory = JavaScriptTypeInventory { + version: JAVASCRIPT_TYPE_INVENTORY_VERSION, + records: records.to_vec(), + }; + let content = serde_json::to_string_pretty(&inventory) + .map_err(|error| format!("Failed to serialize JavaScript type inventory: {error}"))?; + let path = output_dir.join(JAVASCRIPT_TYPE_INVENTORY); + ensure_safe_generated_destination(output_dir, &path)?; + write_file(&path, &format!("{content}\n")) +} + +fn emitted_javascript_type_records( + output_dir: &Path, + previous: &[javascript::JavaScriptTypeLayoutRecord], + current: &[javascript::JavaScriptTypeLayoutRecord], +) -> Result, String> { + let identities = previous + .iter() + .chain(current) + .map(|record| (record.identity.clone(), record.abi_identity.clone())) + .collect::>(); + let previous_implementations = previous + .iter() + .map(|record| (record.identity.clone(), record.implementation_name.clone())) + .collect::>(); + let current_identities = current + .iter() + .map(|record| record.identity.clone()) + .collect::>(); + javascript::javascript_output_targets() + .into_iter() + .filter(|target| { + output_dir + .join(format!("{}.js", target.canonical_module)) + .is_file() + && output_dir + .join(format!("{}.d.ts", target.canonical_module)) + .is_file() + }) + .map(|target| { + let abi_identity = identities.get(&target.identity).cloned().ok_or_else(|| { + format!( + "Missing WinRT ABI identity for JavaScript output `{}.{}`", + target.identity.namespace, target.identity.name + ) + })?; + let compatibility_aliases = target.compatibility_aliases.clone(); + let implementation_name = if current_identities.contains(&target.identity) { + target.projected_name.clone() } else { - owners.insert(name, (module.clone(), signature)); + previous_implementations + .get(&target.identity) + .cloned() + .ok_or_else(|| { + format!( + "Missing implementation name for retained JavaScript output `{}.{}`", + target.identity.namespace, target.identity.name + ) + })? + }; + Ok(javascript::JavaScriptTypeLayoutRecord::new( + target.identity, + target.projected_name, + abi_identity, + ) + .with_implementation_name(implementation_name) + .with_compatibility_aliases(compatibility_aliases)) + }) + .collect() +} + +fn generated_struct_helper_identities(content: &str) -> Vec<(String, String)> { + content + .lines() + .filter_map(|line| { + let declaration = line.trim_start().strip_prefix("const ")?; + let (name, value) = declaration.split_once("_Type = DynWinRtType.structType('")?; + let (identity, _) = value.split_once('\'')?; + (!name.is_empty() && !identity.is_empty()) + .then(|| (name.to_string(), identity.to_string())) + }) + .collect() +} + +fn validate_generated_struct_helper_identities_against( + output_dir: &Path, + current: &BTreeMap, +) -> Result<(), String> { + let mut owners = current + .iter() + .map(|(name, identity)| { + ( + name.clone(), + (identity.clone(), "current generation".to_string()), + ) + }) + .collect::>(); + for target in javascript::javascript_output_targets() { + let path = output_dir.join(format!("{}.js", target.canonical_module)); + if !path.is_file() { + continue; + } + let content = fs::read_to_string(&path) + .map_err(|error| format!("Failed to read {}: {error}", path.display()))?; + for (name, identity) in generated_struct_helper_identities(&content) { + if let Some((existing, existing_module)) = owners.insert( + name.clone(), + (identity.clone(), target.canonical_module.clone()), + ) && existing != identity + { + return Err(format!( + "JavaScript struct helper collision: `{existing}` from `{existing_module}` and \ + `{identity}` from `{}` both export `pack{name}`. Generate these bindings into \ + separate output directories.", + target.canonical_module + )); } } } Ok(()) } -fn native_pod_factory_signature(content: &str, export_name: &str) -> Option { - let pod_name = export_name.strip_prefix("create")?; - if pod_name.is_empty() { - return None; - } - let pod_name = pod_name.strip_suffix("Array").unwrap_or(pod_name); - [ - format!("const _nativeLayout_{pod_name} = "), - format!("const _nativeUnionLayout_{pod_name} = "), - ] - .into_iter() - .find_map(|prefix| { - content - .lines() - .find(|line| line.starts_with(&prefix)) - .map(str::to_string) - }) +fn validate_generated_struct_helper_identities(output_dir: &Path) -> Result<(), String> { + validate_generated_struct_helper_identities_against(output_dir, &BTreeMap::new()) } -fn finalize_com_generation(output_dir: &Path) -> Result<(), String> { - if !has_winrt_root(output_dir) { - write_com_root_compatibility_barrels(output_dir)?; +fn validate_unique_class_output_names(classes: &[meta::ClassMeta]) -> Result<(), String> { + let mut full_name_by_short_name: HashMap<&str, &str> = HashMap::new(); + for class in classes { + match full_name_by_short_name.get(class.name.as_str()) { + Some(existing) if *existing != class.full_name => { + return Err(format!( + "Cannot generate `{}` and `{}` in one output directory because both use \ + the short class name `{}`. Generate them separately or select only one type.", + existing, class.full_name, class.name + )); + } + Some(_) => {} + None => { + full_name_by_short_name.insert(&class.name, &class.full_name); + } + } } - write_bindings_manifest(output_dir) -} - -fn write_com_root_compatibility_barrels(output_dir: &Path) -> Result<(), String> { - let com_dir = output_dir.join("com"); - let com_js_path = com_dir.join("index.js"); - let com_dts_path = com_dir.join("index.d.ts"); - let com_js = fs::read_to_string(&com_js_path) - .map_err(|error| format!("Failed to read {}: {error}", com_js_path.display()))?; - let com_dts = fs::read_to_string(&com_dts_path) - .map_err(|error| format!("Failed to read {}: {error}", com_dts_path.display()))?; - let root_js = com_js.replace(", './", ", './com/"); - let root_dts = com_dts.replace("from './", "from './com/"); - fs::write(output_dir.join("index.js"), &root_js) - .map_err(|error| format!("Failed to write COM compatibility index.js: {error}"))?; - fs::write(output_dir.join("index.d.ts"), root_dts) - .map_err(|error| format!("Failed to write COM compatibility index.d.ts: {error}"))?; Ok(()) } -fn migrate_legacy_com_only_package(output_dir: &Path) -> Result<(), String> { - if has_winrt_root(output_dir) { - return Ok(()); - } - - let package_path = output_dir.join("package.json"); - let index_path = output_dir.join("index.js"); - let index_dts_path = output_dir.join("index.d.ts"); - if !package_path.is_file() || !index_path.is_file() || !index_dts_path.is_file() { - return Ok(()); - } - let package = fs::read_to_string(&package_path) - .map_err(|error| format!("Failed to read {}: {error}", package_path.display()))?; - let index = fs::read_to_string(&index_dts_path) - .map_err(|error| format!("Failed to read {}: {error}", index_dts_path.display()))?; - if !package.contains("\"name\": \"@winapp/bindings\"") - || !(package.contains("\"type\": \"module\"") || package.contains("\"type\": \"commonjs\"")) - || !index.starts_with("// Generated by dynwinrt-codegen") - { - return Ok(()); - } - - let modules = collect_com_index_modules(&index); - if modules.is_empty() { - return Ok(()); - } - - let com_output_dir = output_dir.join("com"); - fs::create_dir_all(&com_output_dir).map_err(|error| { +fn emit_javascript_projected_file( + output_dir: &Path, + mut projected: dynwinrt_codegen::codegen::projected::ProjectedFile, +) -> Result<(), String> { + let target = javascript::configure_projected_file(&mut projected).ok_or_else(|| { format!( - "Failed to create COM output directory '{}': {error}", - com_output_dir.display() + "JavaScript module layout does not contain projected type `{}`", + projected.name ) })?; - for module in modules { - for suffix in [".js", ".d.ts"] { - move_legacy_com_file( - &output_dir.join(format!("{module}{suffix}")), - &com_output_dir.join(format!("{module}{suffix}")), - )?; + let mut js = render_js::render(&projected); + let mut dts = render_dts::render(&projected); + let lifetime = javascript::root_relative_module(&target.canonical_module, "lifetime"); + js = js.replace( + "require('./lifetime.js')", + &format!("require('{lifetime}.js')"), + ); + if target.collides { + if target.identity.kind == javascript::JavaScriptTypeKind::Delegate { + js.push_str(&format!( + "exports.IID_{native} = exports.IID_{projected};\n\ + exports.{native}_PARAM_TYPES = exports.{projected}_PARAM_TYPES;\n", + native = target.identity.name, + projected = target.projected_name, + )); + dts.push_str(&format!( + "\nexport {{ IID_{projected} as IID_{native}, \ + {projected}_PARAM_TYPES as {native}_PARAM_TYPES }};\n\ + export type {native} = {projected};\n", + projected = target.projected_name, + native = target.identity.name, + )); + } else { + if js.contains(&format!("exports.{} =", target.projected_name)) { + js.push_str(&format!( + "exports.{native} = {projected};\n", + native = target.identity.name, + projected = target.projected_name, + )); + } + let projected_iid = format!("exports.IID_{} =", target.projected_name); + if js.contains(&projected_iid) { + js.push_str(&format!( + "exports.IID_{native} = exports.IID_{projected};\n", + native = target.identity.name, + projected = target.projected_name, + )); + } + dts.push_str(&format!( + "\nexport {{ {projected} as {native} }};\n", + projected = target.projected_name, + native = target.identity.name, + )); + if dts.contains(&format!("IID_{}", target.projected_name)) { + dts.push_str(&format!( + "export {{ IID_{projected} as IID_{native} }};\n", + projected = target.projected_name, + native = target.identity.name, + )); + } } } - - for path in [ - output_dir.join("index.js"), - output_dir.join("index.mjs"), - output_dir.join("index.d.ts"), - package_path, - ] { - if path.exists() { - fs::remove_file(&path) - .map_err(|error| format!("Failed to remove {}: {error}", path.display()))?; + for alias in &target.compatibility_aliases { + if target.identity.kind == javascript::JavaScriptTypeKind::Delegate { + js.push_str(&format!( + "exports.IID_{alias} = exports.IID_{projected};\n\ + exports.{alias}_PARAM_TYPES = exports.{projected}_PARAM_TYPES;\n", + projected = target.projected_name, + )); + dts.push_str(&format!( + "\nexport {{ IID_{projected} as IID_{alias}, \ + {projected}_PARAM_TYPES as {alias}_PARAM_TYPES }};\n\ + export type {alias} = {projected};\n", + projected = target.projected_name, + )); + } else { + if js.contains(&format!("exports.{} =", target.projected_name)) { + js.push_str(&format!( + "exports.{alias} = {projected};\n", + projected = target.projected_name, + )); + } + if js.contains(&format!("exports.IID_{} =", target.projected_name)) { + js.push_str(&format!( + "exports.IID_{alias} = exports.IID_{projected};\n", + projected = target.projected_name, + )); + } + dts.push_str(&format!( + "\nexport {{ {projected} as {alias} }};\n", + projected = target.projected_name, + )); + if dts.contains(&format!("IID_{}", target.projected_name)) { + dts.push_str(&format!( + "export {{ IID_{projected} as IID_{alias} }};\n", + projected = target.projected_name, + )); + } } } - write_com_js_barrel(&com_output_dir)?; - finalize_com_generation(output_dir) -} -fn collect_com_index_modules(index: &str) -> BTreeSet { - index - .lines() - .filter_map(|line| { - let (_, module) = line.split_once(" from './")?; - let module = module.strip_suffix(".js';")?; - (!module.is_empty() && !module.contains(['/', '\\'])).then(|| module.to_string()) - }) - .collect() + let js_path = output_dir.join(format!("{}.js", target.canonical_module)); + let dts_path = output_dir.join(format!("{}.d.ts", target.canonical_module)); + write_generated_javascript_file(output_dir, &js_path, &js)?; + write_generated_javascript_file(output_dir, &dts_path, &dts)?; + println!("Generated {}", js_path.display()); + Ok(()) } -fn move_legacy_com_file(source: &Path, destination: &Path) -> Result<(), String> { - if !source.exists() { - return Ok(()); - } - if destination.exists() { - let source_content = fs::read(source) - .map_err(|error| format!("Failed to read {}: {error}", source.display()))?; - let destination_content = fs::read(destination) - .map_err(|error| format!("Failed to read {}: {error}", destination.display()))?; - if source_content != destination_content { +fn ensure_safe_generated_parent(output_dir: &Path, destination: &Path) -> Result<(), String> { + if !output_dir.exists() { + fs::create_dir_all(output_dir).map_err(|error| { + format!( + "Failed to create JavaScript output directory {}: {error}", + output_dir.display() + ) + })?; + } + let relative = destination.strip_prefix(output_dir).map_err(|_| { + format!( + "Generated JavaScript path '{}' is outside output directory '{}'", + destination.display(), + output_dir.display() + ) + })?; + let relative_parent = relative.parent().unwrap_or_else(|| Path::new("")); + let mut current = output_dir.to_path_buf(); + for component in relative_parent.components() { + let std::path::Component::Normal(segment) = component else { return Err(format!( - "Cannot migrate legacy COM file {} because {} already exists with different content", - source.display(), + "Generated JavaScript path '{}' contains an unsafe component", destination.display() )); + }; + current.push(segment); + if current.exists() { + let metadata = fs::symlink_metadata(¤t) + .map_err(|error| format!("Failed to inspect {}: {error}", current.display()))?; + if is_link_or_reparse_point(&metadata) { + return Err(format!( + "Refusing to write generated JavaScript through linked directory '{}'", + current.display() + )); + } + if !metadata.is_dir() { + return Err(format!( + "Generated JavaScript parent '{}' is not a directory", + current.display() + )); + } + } else { + fs::create_dir(¤t) + .map_err(|error| format!("Failed to create {}: {error}", current.display()))?; } - fs::remove_file(source) - .map_err(|error| format!("Failed to remove {}: {error}", source.display()))?; - return Ok(()); } - - fs::rename(source, destination).map_err(|error| { - format!( - "Failed to migrate legacy COM file {} to {}: {error}", - source.display(), - destination.display() - ) - }) + let resolved_root = fs::canonicalize(output_dir) + .map_err(|error| format!("Failed to resolve {}: {error}", output_dir.display()))?; + let resolved_parent = fs::canonicalize(¤t) + .map_err(|error| format!("Failed to resolve {}: {error}", current.display()))?; + if !resolved_parent.starts_with(&resolved_root) { + return Err(format!( + "Resolved JavaScript parent '{}' escapes output directory '{}'", + resolved_parent.display(), + resolved_root.display() + )); + } + Ok(()) } -fn has_winrt_root(output_dir: &Path) -> bool { - ["index.mjs", "index.proxy.js", "lifetime.js"] - .iter() - .any(|name| output_dir.join(name).is_file()) +fn is_link_or_reparse_point(metadata: &fs::Metadata) -> bool { + let mut is_link = metadata.file_type().is_symlink(); + #[cfg(windows)] + { + use std::os::windows::fs::MetadataExt; + const FILE_ATTRIBUTE_REPARSE_POINT: u32 = 0x400; + is_link |= metadata.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0; + } + is_link } -fn write_bindings_manifest(output_dir: &Path) -> Result<(), String> { - let has_winrt_root = has_winrt_root(output_dir); - let winrt_subpath_names = if has_winrt_root { - collect_subpath_names_from_dir(output_dir) - } else { - BTreeSet::new() - }; - let com_subpath_names = collect_com_subpath_names(&output_dir.join("com"))?; - let content = package::render_bindings_package_json(&package::BindingsPackageManifestInput { - has_winrt_root, - winrt_subpath_names: &winrt_subpath_names, - com_subpath_names: &com_subpath_names, - }); - let path = output_dir.join("package.json"); - fs::write(&path, content) - .map_err(|error| format!("Failed to write {}: {error}", path.display())) +fn ensure_generated_tree_has_no_links(output_dir: &Path) -> Result<(), String> { + fn visit(current: &Path) -> Result<(), String> { + let entries = fs::read_dir(current) + .map_err(|error| format!("Failed to read {}: {error}", current.display()))?; + for entry in entries { + let entry = + entry.map_err(|error| format!("Failed to read directory entry: {error}"))?; + let path = entry.path(); + let metadata = fs::symlink_metadata(&path) + .map_err(|error| format!("Failed to inspect {}: {error}", path.display()))?; + if is_link_or_reparse_point(&metadata) { + return Err(format!( + "Generated JavaScript output contains linked path '{}'", + path.display() + )); + } + if metadata.is_dir() { + visit(&path)?; + } + } + Ok(()) + } + visit(output_dir) } -fn collect_com_subpath_names(com_output_dir: &Path) -> Result, String> { - let index_path = com_output_dir.join("index.d.ts"); - if !index_path.is_file() { - return Ok(BTreeSet::new()); +fn ensure_safe_generated_destination(output_dir: &Path, destination: &Path) -> Result<(), String> { + ensure_safe_generated_parent(output_dir, destination)?; + match fs::symlink_metadata(destination) { + Ok(metadata) if is_link_or_reparse_point(&metadata) => Err(format!( + "Refusing to write generated JavaScript through linked file '{}'", + destination.display() + )), + Ok(_) => Ok(()), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()), + Err(error) => Err(format!( + "Failed to inspect generated JavaScript destination {}: {error}", + destination.display() + )), } - let index = fs::read_to_string(&index_path) - .map_err(|error| format!("Failed to read {}: {error}", index_path.display()))?; - Ok(collect_com_index_modules(&index)) } -fn collect_com_cjs_exports(content: &str) -> BTreeSet { - content - .lines() - .filter_map(|line| { - let line = line.trim_start(); - let rest = line.strip_prefix("exports.")?; - let name = rest - .chars() - .take_while(|character| { - character.is_ascii_alphanumeric() || *character == '_' || *character == '$' - }) - .collect::(); - (!name.is_empty() && rest[name.len()..].trim_start().starts_with('=')).then_some(name) - }) - .collect() +fn write_generated_javascript_file( + output_dir: &Path, + path: &Path, + content: &str, +) -> Result<(), String> { + ensure_safe_generated_destination(output_dir, path)?; + if path.is_file() + && !fs::read_to_string(path) + .map(|existing| existing.starts_with("// Generated by dynwinrt-codegen")) + .unwrap_or(false) + { + return Err(format!( + "Refusing to overwrite non-generated JavaScript binding '{}'", + path.display() + )); + } + write_file(path, content) } -fn write_lifetime_module(output_dir: &Path) -> Result<(), String> { - let js = "'use strict';\n\ -let activeScope = null;\n\ -const trackedScopes = new WeakMap();\n\ -function trackProjectedValue(value, typeName) {\n\ - activeScope?.track(value, typeName);\n\ - return value;\n\ -}\n\ -function isObjectLike(value) {\n\ - return value !== null && (typeof value === 'object' || typeof value === 'function');\n\ -}\n\ -function removeTracking(scope, value) {\n\ - const scopes = trackedScopes.get(value);\n\ - if (!scopes) return;\n\ - scopes.delete(scope);\n\ - if (scopes.size === 0) trackedScopes.delete(value);\n\ -}\n\ -function untrackProjectedValue(value) {\n\ - const scopes = trackedScopes.get(value);\n\ - if (!scopes) return;\n\ - for (const scope of [...scopes]) scope.untrack(value);\n\ -}\n\ -function castProjectedValueOwned(value, iid, typeName) {\n\ - let projected;\n\ - try { projected = value.cast(iid); }\n\ - catch (error) {\n\ - try { value.release(); } catch {}\n\ - throw error;\n\ - }\n\ - if (projected !== value) {\n\ - try { value.release(); }\n\ - catch (error) {\n\ - try { projected.release(); } catch {}\n\ - throw error;\n\ - }\n\ - }\n\ - return trackProjectedValue(projected, typeName);\n\ -}\n\ -function castProjectedValueBorrowed(value, iid, typeName) {\n\ - return trackProjectedValue(value.cast(iid), typeName);\n\ -}\n\ -const castProjectedValue = castProjectedValueOwned;\n\ -function projectAs(value, type) {\n\ - const source = isObjectLike(value) && '_obj' in value ? value._obj : value;\n\ - if (!isObjectLike(source)) throw new TypeError('projectAs requires a projected value or wrapper.');\n\ - if (!isObjectLike(type) || typeof type._fromNativeBorrowed !== 'function') {\n\ - throw new TypeError('projectAs requires a generated runtime class type.');\n\ - }\n\ - const projected = type._fromNativeBorrowed(source);\n\ - if (!isObjectLike(projected) || !('_obj' in projected)) {\n\ - throw new TypeError('The generated runtime class returned an invalid projection.');\n\ - }\n\ - return projected;\n\ -}\n\ -function releaseProjected(value) {\n\ - if (!isObjectLike(value) || !('_obj' in value)) {\n\ - throw new TypeError('releaseProjected requires a generated projected wrapper.');\n\ - }\n\ - const projected = value._obj;\n\ - if (!isObjectLike(projected) || typeof projected.release !== 'function') {\n\ - throw new TypeError('The projected wrapper does not contain a releasable native value.');\n\ - }\n\ - projected.release();\n\ - untrackProjectedValue(projected);\n\ -}\n\ -function createProjectedLifetimeScope() {\n\ - const previousScope = activeScope;\n\ - const registry = new Map();\n\ - let disposed = false;\n\ - const scope = {\n\ - get disposed() { return disposed; },\n\ - track(value, typeName) {\n\ - if (disposed) throw new Error('Cannot track values in a disposed projection scope.');\n\ - if (registry.has(value)) return;\n\ - registry.set(value, typeName);\n\ - let scopes = trackedScopes.get(value);\n\ - if (!scopes) trackedScopes.set(value, scopes = new Set());\n\ - scopes.add(scope);\n\ - },\n\ - untrack(value) {\n\ - registry.delete(value);\n\ - removeTracking(scope, value);\n\ - },\n\ - dispose() {\n\ - if (disposed) return;\n\ - if (activeScope !== scope) throw new Error('Projection lifetime scopes must be disposed in LIFO order.');\n\ - let firstError;\n\ - for (const [value] of [...registry].reverse()) {\n\ - try { value.release(); scope.untrack(value); }\n\ - catch (error) { firstError ??= error; }\n\ - }\n\ - if (firstError !== undefined) throw firstError;\n\ - disposed = true;\n\ - activeScope = previousScope;\n\ - },\n\ - };\n\ - activeScope = scope;\n\ - return scope;\n\ -}\n\ -exports.trackProjectedValue = trackProjectedValue;\n\ -exports.castProjectedValue = castProjectedValue;\n\ -exports.castProjectedValueOwned = castProjectedValueOwned;\n\ -exports.castProjectedValueBorrowed = castProjectedValueBorrowed;\n\ -exports.projectAs = projectAs;\n\ -exports.releaseProjected = releaseProjected;\n\ -exports.createProjectedLifetimeScope = createProjectedLifetimeScope;\n"; - let dts = "export declare function trackProjectedValue(value: T, typeName: string): T;\n\ -export declare function castProjectedValue(value: T, iid: unknown, typeName: string): T;\n\ -export declare function castProjectedValueOwned(value: T, iid: unknown, typeName: string): T;\n\ -export declare function castProjectedValueBorrowed(value: T, iid: unknown, typeName: string): T;\n\ -export interface ProjectedType {\n\ - readonly prototype: T;\n\ -}\n\ -/**\n\ - * Borrows a raw projected value or wrapper and exposes it as a generated type.\n\ - * The input remains valid; the returned projection owns its interface view and\n\ - * must be released independently or retained by a projected lifetime scope.\n\ - */\n\ -export declare function projectAs(value: unknown, type: ProjectedType): T;\n\ -export declare function releaseProjected(value: object): void;\n\ -export interface ProjectedLifetimeScope {\n\ - readonly disposed: boolean;\n\ - dispose(): void;\n\ -}\n\ -export declare function createProjectedLifetimeScope(): ProjectedLifetimeScope;\n"; - fs::write(output_dir.join("lifetime.js"), js) - .map_err(|e| format!("Failed to write lifetime.js: {e}"))?; - fs::write(output_dir.join("lifetime.d.ts"), dts) - .map_err(|e| format!("Failed to write lifetime.d.ts: {e}"))?; - Ok(()) -} +fn generate_js_files( + output_dir: &Path, + all_classes: &[meta::ClassMeta], + all_interfaces: &[meta::InterfaceMeta], + all_enums: &[TypeMeta], + shared_interfaces: &[meta::InterfaceMeta], + known_types: &HashSet, + delegate_type_names: &HashSet, + shared_iids: &HashSet, + delegate_sigs: &HashMap, + delegate_sig_refs: &HashMap>, + delegate_param_wraps: &HashMap>, +) -> Result<(), String> { + // Exclusive interfaces paired with a runtime class are implementation + // details. The projected layout already qualifies genuine cross-namespace + // collisions, so this name check only removes those class-owned entries. + let class_names: HashSet<&str> = all_classes.iter().map(|c| c.name.as_str()).collect(); -fn render_index_from_existing_js_files(output_dir: &Path) -> Result { - let mut out = String::from("// Generated by dynwinrt-codegen \u{2014} do not edit\n"); - // Two-pass so dedup is deterministic regardless of fs::read_dir order: - // pass 1 collects (stem, exports) and sorts by stem; pass 2 dedupes so - // the alphabetically-first module wins each shared symbol (interface - // files like `IStringable.js` win over classes that re-export the IID). - let mut candidates: Vec<(String, Vec)> = Vec::new(); - let entries = fs::read_dir(output_dir).map_err(|e| { - format!( - "Failed to read output directory {}: {}", - output_dir.display(), - e - ) - })?; - for entry in entries.flatten() { - let path = entry.path(); - let Some(fname) = path.file_name().and_then(|s| s.to_str()) else { - continue; - }; - let Some(stem) = fname.strip_suffix(".js") else { - continue; - }; - if matches!(stem, "index" | "index.proxy" | "index.getter") { + // Interface entries with no IID and no generic PIID are synthesized stubs + // (typically parameterized instantiations named after a class type + // parameter, e.g. `UIElement` from `IIterable`). They must not + // be emitted — the file would have a broken `registerInterface` call with + // no matching IID declaration and would overwrite any real class file of + // the same name. + fn is_emittable_interface(iface: &meta::InterfaceMeta) -> bool { + !iface.iid.is_empty() + } + + for iface in shared_interfaces { + if class_names.contains(iface.name.as_str()) { continue; } - let content = match fs::read_to_string(&path) { - Ok(c) => c, - Err(_) => continue, - }; - let mut names = collect_public_exports_from_js(&content); - names.sort(); - names.dedup(); - if names.is_empty() { + if !is_emittable_interface(iface) { continue; } - candidates.push((stem.to_string(), names)); + let projected = project::project_interface( + iface, + known_types, + delegate_type_names, + delegate_sigs, + delegate_sig_refs, + delegate_param_wraps, + ); + emit_javascript_projected_file(output_dir, projected)?; } - // Prefer the canonical owner (module stem == export name) so shared - // symbols like `IMemoryBuffer` come from `IMemoryBuffer.js`, not from an - // alphabetically earlier consumer like `BitmapBuffer.js`. - let canonical: BTreeSet = candidates - .iter() - .filter(|(stem, names)| names.iter().any(|n| n == stem)) - .map(|(stem, _)| stem.clone()) - .collect(); - candidates.sort_by(|a, b| a.0.cmp(&b.0)); - let mut seen_exports: BTreeSet = BTreeSet::new(); - let mut modules: Vec<(String, Vec)> = Vec::new(); - for (stem, names) in candidates { - let filtered: Vec = names - .into_iter() - .filter(|name| { - if canonical.contains(name) && name != &stem { - return false; - } - seen_exports.insert(name.clone()) - }) - .collect(); - if filtered.is_empty() { + for iface in all_interfaces { + if class_names.contains(iface.name.as_str()) { continue; } - modules.push((stem, filtered)); - } - for (module, names) in modules { - out.push_str(&format!( - "export {{ {} }} from './{}.js';\n", - names.join(", "), - module - )); - } - Ok(out) -} - -fn collect_public_exports_from_js(content: &str) -> Vec { - let mut names = Vec::new(); - for line in content.lines() { - let line = line.trim_start(); - let Some(rest) = line.strip_prefix("exports.") else { - continue; - }; - let name: String = rest - .chars() - .take_while(|c| c.is_ascii_alphanumeric() || *c == '_' || *c == '$') - .collect(); - if name.is_empty() { + if !is_emittable_interface(iface) { continue; } - // Keep IIDs, parameter type arrays, and struct type descriptors scoped - // to their per-type modules. Root barrels should expose user-facing - // classes, enums, pack/unpack helpers, and interfaces only. - if name == "trackProjectedValue" - || name == "castProjectedValue" - || name == "castProjectedValueOwned" - || name == "castProjectedValueBorrowed" - || name.starts_with("__") - || name.starts_with("IID_") - || name.ends_with("_PARAM_TYPES") - || name.ends_with("_Type") - { - continue; + let projected = project::project_interface( + iface, + known_types, + delegate_type_names, + delegate_sigs, + delegate_sig_refs, + delegate_param_wraps, + ); + emit_javascript_projected_file(output_dir, projected)?; + } + for en in all_enums { + if let TypeMeta::Enum { name, .. } = en { + if name.contains('<') { + continue; + } // skip CLR projection types + if class_names.contains(name.as_str()) { + continue; + } + if let Some(projected) = project::project_enum(en) { + emit_javascript_projected_file(output_dir, projected)?; + } } - names.push(name); } - names -} - -/// Enumerate the per-type `.js` files in `output_dir` and return their -/// basenames (without extension) sorted alphabetically. Excludes barrel files -/// (`index.js`, `index.mjs`, `index.proxy.js`, and legacy `index.getter.js`). -/// Non-existent or unreadable -/// directories return an empty set — the caller decides what to do. -fn collect_subpath_names_from_dir(output_dir: &Path) -> BTreeSet { - const BARREL_STEMS: &[&str] = &["index", "index.getter", "index.proxy"]; - let mut names: BTreeSet = BTreeSet::new(); - let Ok(entries) = fs::read_dir(output_dir) else { - return names; + // First pass: emit "real" classes. A class is emit-worthy if any of these + // hold: + // * it has a default interface with a resolvable IID (normal + // activatable / composable class), OR + // * it has factory/statics interfaces (statics-only utility classes such + // as `LimitedAccessFeatures`, `AICapabilities`, `PowerManager`), OR + // * it has required or overridable methods callable on an inbound obj. + // + // Only synthetic parameterized "instantiations" (e.g. `IIterable` + // reprojected as a class stub) with nothing at all fall through to the + // stub-emission pass below. + let mut emitted_class_names: HashSet = HashSet::new(); + let class_is_usable = |class: &meta::ClassMeta| -> bool { + let has_default_iid = class + .default_interface + .as_ref() + .map_or(false, |di| !di.iid.is_empty()); + let has_statics_or_factory = + !class.static_interfaces.is_empty() || !class.factory_interfaces.is_empty(); + let has_required = !class.required_interfaces.is_empty(); + has_default_iid || has_statics_or_factory || has_required }; - for entry in entries.flatten() { - let path = entry.path(); - let Some(fname) = path.file_name().and_then(|s| s.to_str()) else { + for class in all_classes { + if !class_is_usable(class) { continue; - }; - // Match `Foo.js` but NOT `Foo.d.ts` or `Foo.mjs`. - let Some(stem) = fname.strip_suffix(".js") else { + } + let projected = project::project_class( + class, + known_types, + delegate_type_names, + shared_iids, + delegate_sigs, + delegate_sig_refs, + delegate_param_wraps, + ); + emit_javascript_projected_file(output_dir, projected)?; + emitted_class_names.insert(class.name.clone()); + } + // Second pass: emit stubs for genuinely empty class shells (parameterized + // synthetics from the projection layer that carry no methods). Stubs keep + // ESM barrel imports linkable even when the underlying type isn't + // constructible at runtime. + for class in all_classes { + if class_is_usable(class) { continue; - }; - if BARREL_STEMS.iter().any(|b| stem == *b) { + } + if emitted_class_names.contains(&class.name) { continue; } - names.insert(stem.to_string()); + let mut stub_js = format!( + "// Generated by dynwinrt-codegen \u{2014} do not edit\n\ + // Placeholder for a class whose default interface has no IID in\n\ + // the loaded winmd graph. Any attempt to use it will throw.\n\ + const __unavailable = () => {{ throw new Error(\"'{name}' has no default interface in the loaded winmd graph and cannot be constructed. Add its owning package to `additionalWinmds` / `additionalRefs`.\"); }};\n\ + class {name} {{ constructor() {{ __unavailable(); }} }}\n\ + exports.{name} = {name};\n", + name = class.name, + ); + let mut stub_dts = format!( + "// Generated by dynwinrt-codegen \u{2014} do not edit\n\ + // Placeholder: throwing at construction. Typed as a class so + // other .d.ts files can still use `{name}` as a parameter / + // return type.\n\ + export declare class {name} {{ private constructor(); }}\n", + name = class.name, + ); + let target = javascript::javascript_output_target(&class.name).ok_or_else(|| { + format!( + "JavaScript module layout does not contain projected type `{}`", + class.name + ) + })?; + if target.collides { + stub_js.push_str(&format!( + "exports.{native} = {projected};\n", + native = target.identity.name, + projected = target.projected_name, + )); + stub_dts.push_str(&format!( + "export {{ {projected} as {native} }};\n", + projected = target.projected_name, + native = target.identity.name, + )); + } + for alias in &target.compatibility_aliases { + stub_js.push_str(&format!( + "exports.{alias} = {projected};\n", + projected = target.projected_name, + )); + stub_dts.push_str(&format!( + "export {{ {projected} as {alias} }};\n", + projected = target.projected_name, + )); + } + let js_path = output_dir.join(format!("{}.js", target.canonical_module)); + let dts_path = output_dir.join(format!("{}.d.ts", target.canonical_module)); + write_generated_javascript_file(output_dir, &js_path, &stub_js)?; + write_generated_javascript_file(output_dir, &dts_path, &stub_dts)?; + println!("Generated {}", js_path.display()); + emitted_class_names.insert(class.name.clone()); } - names + + // Post-process: strip imports that reference non-existent sibling files. + // This handles cases where a class pulls in a type reference (e.g. WinUI XAML + // classes referencing Microsoft.UI.Composition types whose winmd was removed + // in later Windows App SDK versions) but the target file was never emitted. + // Rather than leave the entire binding set broken at load time, we drop the + // import — any methods that depended on that type will surface as runtime + // ReferenceErrors when actually called, but the module loads. + strip_broken_imports(output_dir)?; + + Ok(()) } -fn strip_broken_imports(output_dir: &Path) -> Result<(), String> { - use dynwinrt_codegen::codegen::project::get_import_name; - use std::collections::HashSet as StdHashSet; - - let mut existing: StdHashSet = StdHashSet::new(); - if let Ok(read_dir) = fs::read_dir(output_dir) { - for entry in read_dir.flatten() { - if let Some(name) = entry.file_name().to_str() { - if let Some(stem) = name.strip_suffix(".js") { - existing.insert(stem.to_string()); - } - } - } - } +/// Write the four root barrel entries plus `package.json` alongside canonical +/// namespaced implementations. +/// +/// The four barrels are: +/// * `index.js` — CJS `Object.defineProperty` getter barrel — real +/// values, lazy, default for `require('@winapp/bindings')`. +/// * `index.mjs` — standard ESM re-export barrel — real values, +/// tree-shakable for bundlers. +/// * `index.proxy.js` — legacy CJS Proxy barrel — lexer-visible +/// `exports.X = ...` assignments for opt-in +/// compatibility via `@winapp/bindings/proxy`. +/// * `index.d.ts` — TypeScript declarations shared across every path. +/// +/// Root barrels point directly at canonical modules. Package subpaths expose +/// only canonical namespace paths. +fn write_js_barrel_and_manifest(output_dir: &Path, index_content: &str) -> Result<(), String> { + let js_path = output_dir.join("index.js"); + let mjs_path = output_dir.join("index.mjs"); + let proxy_path = output_dir.join("index.proxy.js"); + let dts_path = output_dir.join("index.d.ts"); + let _ = index_content; + write_lifetime_module(output_dir)?; - // If `--import-name ./runtime.js` was used, that stem is not one of the - // emitted modules but must not be stripped. - let runtime_name = get_import_name(); - if let Some(runtime_stem) = runtime_name - .strip_prefix("./") - .and_then(|s| s.strip_suffix(".js").or(Some(s))) - { - existing.insert(runtime_stem.to_string()); + // Clean up any stale `.index.ts` cache from older codegen versions. + let stale = output_dir.join(".index.ts"); + if stale.exists() { + ensure_safe_generated_destination(output_dir, &stale)?; + fs::remove_file(&stale) + .map_err(|error| format!("Failed to remove {}: {error}", stale.display()))?; } - existing.insert("lifetime".to_string()); - // Three patterns to strip when the target sibling doesn't exist: - // - // 1. Legacy ESM import (in case render_esm output leaks through): - // import { X } from './Foo.js'; - // - // 2. CJS lazy loader triplet emitted by convert_to_cjs_with_lazy (class files): - // let __m_Foo; - // const __load_Foo = () => (__m_Foo ??= require('./Foo.js')); - // const X = __lazy(__load_Foo, 'X'); // one per imported symbol - // - // 3. Index-level lazy exports emitted by esm_index_to_cjs_lazy: - // exports.X = undefined; - // Object.defineProperty(exports, 'X', { ... get() { return require('./Foo.js').X; } }); - // Both lines reference the same missing target and must go together. - let esm_import_re = regex::Regex::new(r#"(?m)^import \{[^}]*\} from '\./([^']+)\.js';\r?\n"#) - .map_err(|e| format!("regex error: {}", e))?; + // Remove the previous opt-in getter barrel name if it exists from older + // generated output. `index.js` is now the getter barrel and + // `index.proxy.js` is the explicit compatibility path. + let stale_getter = output_dir.join("index.getter.js"); + if stale_getter.exists() { + ensure_safe_generated_destination(output_dir, &stale_getter)?; + fs::remove_file(&stale_getter) + .map_err(|error| format!("Failed to remove {}: {error}", stale_getter.display()))?; + } - // Class-file lazy loader block. New shape: - // let __m_Foo; - // const __load_Foo = () => (__m_Foo ??= require('./Foo.js')); - // const __get_X = () => __load_Foo().X; // one per imported symbol - let cjs_lazy_re = regex::Regex::new( - r"(?ms)^let __m_[A-Za-z0-9_]+;\r?\nconst __load_[A-Za-z0-9_]+ = \(\) => \(__m_[A-Za-z0-9_]+ \?\?= require\('\./([^']+)\.js'\)\);\r?\n(?:const __get_[A-Za-z0-9_]+ = \(\) => __load_[A-Za-z0-9_]+\(\)\.[A-Za-z0-9_]+;\r?\n)*", - ) - .map_err(|e| format!("regex error: {}", e))?; + // Sweep index.js and any other files that still reference sibling modules + // that were skipped by class/interface filters during emission. + strip_broken_imports(output_dir)?; - // Class-file eager destructured require: - // const { IID_X, X_PARAM_TYPES } = require('./Foo.js'); - // Emitted alongside the lazy block for symbols the native runtime needs - // as concrete values (IIDs, DynWinRtType arrays, struct type descriptors). - let cjs_eager_re = - regex::Regex::new(r"(?m)^const \{[^}]+\} = require\('\./([^']+)\.js'\);\r?\n") - .map_err(|e| format!("regex error: {}", e))?; + // Build the barrel from what actually landed on disk rather than from raw + // metadata. This avoids root ESM/CJS barrels referencing files or helper + // exports that were filtered out (for example ref-only WinUI controls such + // as CompositionTarget). + let index_content = render_index_from_existing_js_files(output_dir)?; - // Index-file lazy export line emitted by `esm_index_to_cjs_lazy`: - // { let _m; exports.NAME = __lazy(() => (_m ??= require('./Foo.js')).NAME); } - // captures the module basename in group 1. - let index_dp_re = regex::Regex::new( - r"(?m)^\{ let _m; exports\.[A-Za-z0-9_]+ = __lazy\(\(\) => \(_m \?\?= require\('\./([^']+)\.js'\)\)\.[A-Za-z0-9_]+\); \}\r?\n", - ) - .map_err(|e| format!("regex error: {}", e))?; + let js_content = typescript::esm_index_to_cjs_getter(&index_content); + ensure_safe_generated_destination(output_dir, &js_path)?; + fs::write(&js_path, &js_content) + .map_err(|e| format!("Failed to write {}: {}", js_path.display(), e))?; - let read_dir = match fs::read_dir(output_dir) { - Ok(r) => r, - Err(_) => return Ok(()), - }; - for entry in read_dir.flatten() { - let path = entry.path(); - let name = match path.file_name().and_then(|s| s.to_str()) { - Some(n) => n, - None => continue, - }; - if !name.ends_with(".js") { - continue; - } - let content = match fs::read_to_string(&path) { - Ok(c) => c, - Err(_) => continue, - }; - let mut changed = false; + let mjs_content = typescript::esm_index_to_esm(&index_content); + ensure_safe_generated_destination(output_dir, &mjs_path)?; + fs::write(&mjs_path, &mjs_content) + .map_err(|e| format!("Failed to write {}: {}", mjs_path.display(), e))?; - // 1. CJS lazy loaders for missing targets (class files). - let filtered = cjs_lazy_re.replace_all(&content, |caps: ®ex::Captures| { - let target = &caps[1]; - if existing.contains(target) { - caps[0].to_string() - } else { - changed = true; - String::new() - } - }); + let proxy_content = typescript::esm_index_to_cjs_lazy(&index_content); + ensure_safe_generated_destination(output_dir, &proxy_path)?; + fs::write(&proxy_path, &proxy_content) + .map_err(|e| format!("Failed to write {}: {}", proxy_path.display(), e))?; - // 1b. CJS eager destructured requires for missing sibling modules. - let filtered = cjs_eager_re.replace_all(&filtered, |caps: ®ex::Captures| { - let target = &caps[1]; - if existing.contains(target) { - caps[0].to_string() - } else { - changed = true; - String::new() - } - }); + ensure_safe_generated_destination(output_dir, &dts_path)?; + fs::write(&dts_path, &index_content) + .map_err(|e| format!("Failed to write {}: {}", dts_path.display(), e))?; - // 2. Index lazy-export lines. The new form has a single `{ let _m; ... }` - // block per export; captures the module basename. - let filtered = index_dp_re.replace_all(&filtered, |caps: ®ex::Captures| { - let target = &caps[1]; - if existing.contains(target) { - caps[0].to_string() - } else { - changed = true; - String::new() - } - }); + write_bindings_manifest(output_dir)?; - // 3. Legacy ESM imports (defence-in-depth if pipeline ever emits ESM). - let filtered = esm_import_re.replace_all(&filtered, |caps: ®ex::Captures| { - let target = &caps[1]; - if existing.contains(target) { - caps[0].to_string() - } else { - changed = true; - String::new() - } - }); - if changed { - fs::write(&path, filtered.as_bytes()) - .map_err(|e| format!("Failed to write {}: {}", path.display(), e))?; - } - } + println!("Generated {}", js_path.display()); Ok(()) } -fn generate_py_files( - output_dir: &Path, - all_classes: &[meta::ClassMeta], - all_interfaces: &[meta::InterfaceMeta], - all_enums: &[TypeMeta], - shared_interfaces: &[meta::InterfaceMeta], - known_types: &HashSet, - delegate_type_names: &HashSet, - shared_iids: &HashSet, - pyi: bool, -) -> Result<(), String> { - use dynwinrt_codegen::codegen::python_stub; - - write_file( - &output_dir.join("_runtime.py"), - &python::generate_runtime_support_module(), - )?; - if pyi { - write_file( - &output_dir.join("_runtime.pyi"), - &python_stub::generate_runtime_support_stub(), - )?; - write_file( - &output_dir.join("_typing.pyi"), - &python_stub::generate_typing_support_module(), - )?; +fn prepare_com_generation_manifest( + com_output_dir: &Path, + updated_roots: &BTreeMap>, +) -> Result { + let path = com_output_dir.join(COM_MANIFEST_FILE); + let mut manifest = if path.exists() { + let content = fs::read_to_string(&path) + .map_err(|error| format!("Failed to read {}: {error}", path.display()))?; + serde_json::from_str::(&content).map_err(|error| { + format!( + "Invalid COM generation manifest {}: {error}", + path.display() + ) + })? + } else { + ComGenerationManifest { + version: 1, + roots: BTreeMap::new(), + } + }; + if manifest.version != 1 { + return Err(format!( + "Unsupported COM generation manifest version {} in {}", + manifest.version, + path.display() + )); } - let mut generated_modules = HashSet::new(); - let mut struct_interfaces = all_interfaces.to_vec(); - struct_interfaces.extend_from_slice(shared_interfaces); - let structs = python::package_structs(all_classes, &struct_interfaces); - - // A runtime class owns its public identity when metadata also exposes an - // interface or enum with the same namespace/name. Generate in precedence - // order and render each final module exactly once. - for class in all_classes { - let module = python::python_module_name(&class.namespace, &class.name); - if !generated_modules.insert(module.clone()) { - continue; - } - let code = python::generate_class(class, known_types, delegate_type_names, shared_iids); - let filepath = output_dir.join(format!("{module}.py")); - write_file(&filepath, &code)?; - println!("Generated {}", filepath.display()); - if pyi { - let stub = python_stub::generate_class_stub( - class, - known_types, - delegate_type_names, - shared_iids, - ); - write_file(&output_dir.join(format!("{module}.pyi")), &stub)?; - } + let previous_files = updated_roots + .keys() + .filter_map(|root| manifest.roots.get(root)) + .flatten() + .cloned() + .collect::>(); + for (root, files) in updated_roots { + manifest.roots.insert(root.clone(), files.clone()); } - for en in all_enums { - if let TypeMeta::Enum { - namespace, name, .. - } = en + let retained_files = manifest + .roots + .values() + .flatten() + .cloned() + .collect::>(); + let stale_files = previous_files + .difference(&retained_files) + .cloned() + .collect::>(); + for stale in &stale_files { + let relative = Path::new(stale); + if relative.components().count() != 1 + || !(stale.ends_with(".js") || stale.ends_with(".d.ts")) { - let module = python::python_module_name(namespace, name); - if !generated_modules.insert(module.clone()) { - continue; - } - if let Some(code) = python::generate_enum(en) { - let filepath = output_dir.join(format!("{module}.py")); - write_file(&filepath, &code)?; - println!("Generated {}", filepath.display()); - } - if pyi { - if let Some(stub) = python_stub::generate_enum_stub(en) { - let p = output_dir.join(format!("{module}.pyi")); - write_file(&p, &stub)?; - } - } - } - } - for iface in all_interfaces.iter().chain(shared_interfaces) { - let module = python::python_module_name(&iface.namespace, &iface.name); - if !generated_modules.insert(module.clone()) { - continue; - } - let code = python::generate_interface(iface, known_types, delegate_type_names); - let filepath = output_dir.join(format!("{module}.py")); - write_file(&filepath, &code)?; - println!("Generated {}", filepath.display()); - if pyi { - let stub = - python_stub::generate_interface_stub(iface, known_types, delegate_type_names); - write_file(&output_dir.join(format!("{module}.pyi")), &stub)?; - } - } - for typ in &structs { - let TypeMeta::Struct { - namespace, name, .. - } = typ - else { - continue; - }; - let module = python::python_module_name(namespace, name); - if !generated_modules.insert(module.clone()) { return Err(format!( - "Python struct module `{namespace}.{name}` collides with another generated type" + "Refusing unsafe path `{stale}` in COM generation manifest {}", + path.display() )); } - if let Some(code) = python::generate_struct(typ) { - let filepath = output_dir.join(format!("{module}.py")); - write_file(&filepath, &code)?; - println!("Generated {}", filepath.display()); - } - if pyi { - if let Some(stub) = python_stub::generate_struct_stub(typ) { - write_file(&output_dir.join(format!("{module}.pyi")), &stub)?; - } - } - } - if pyi { - let marker = output_dir.join("py.typed"); - write_file(&marker, "")?; } - Ok(()) -} - -#[derive(Default)] -struct PythonNamespaceGroup { - classes: Vec, - interfaces: Vec, - enums: Vec, - structs: Vec, + Ok(ComManifestUpdate { + manifest, + stale_files, + }) } -#[derive(Clone, Debug, Eq, Hash, PartialEq)] -struct PythonGeneratedType { - kind: String, - identity: python::PythonTypeIdentity, -} - -fn write_python_package_indexes( - output_dir: &Path, - classes: &[meta::ClassMeta], - interfaces: &[meta::InterfaceMeta], - enums: &[TypeMeta], - pyi: bool, - append: bool, +fn apply_com_generation_manifest( + com_output_dir: &Path, + update: ComManifestUpdate, ) -> Result<(), String> { - use dynwinrt_codegen::codegen::python_stub; - - let current_structs = python::package_structs(classes, interfaces); - let current_types = python_generated_types(classes, interfaces, enums); - let mut all_types = if append { - read_python_type_inventory(output_dir)? - } else { - Vec::new() - }; - all_types.extend(current_types); - let mut seen_types = HashSet::new(); - all_types.retain(|typ| seen_types.insert(typ.clone())); - - let module_identities = all_types - .iter() - .map(|typ| typ.identity.clone()) - .collect::>(); - let _layout = python::install_python_module_layout(module_identities.clone())?; - validate_python_public_identities(&module_identities)?; - - let mut interface_counts = HashMap::::new(); - for typ in &all_types { - if typ.kind == "interface" { - *interface_counts - .entry(typ.identity.name.clone()) - .or_default() += 1; + let output_dir = com_output_dir.parent().unwrap_or(com_output_dir); + let path = com_output_dir.join(COM_MANIFEST_FILE); + for stale in &update.stale_files { + let stale_path = com_output_dir.join(stale); + ensure_safe_generated_destination(output_dir, &stale_path)?; + if stale_path.exists() { + fs::remove_file(&stale_path) + .map_err(|error| format!("Failed to remove {}: {error}", stale_path.display()))?; } } - if let Some((name, _)) = interface_counts.iter().find(|(_, count)| **count > 1) { - return Err(format!( - "Python generation cannot safely project multiple interfaces named `{name}`; \ - their delegate and generic runtime symbols are ambiguous" - )); - } - - let mut counts = HashMap::::new(); - for typ in &all_types { - *counts.entry(typ.identity.name.clone()).or_default() += 1; - } - let suppressed_root_names = counts - .iter() - .filter(|(_, count)| **count > 1) - .map(|(name, _)| name.clone()) - .collect::>(); - let root_classes = classes - .iter() - .filter(|class| counts[&class.name] == 1) - .cloned() - .collect::>(); - let root_interfaces = interfaces - .iter() - .filter(|interface| counts[&interface.name] == 1) - .cloned() - .collect::>(); - let root_enums = enums - .iter() - .filter(|typ| matches!(typ, TypeMeta::Enum { name, .. } if counts[name] == 1)) - .cloned() - .collect::>(); - let root_structs = current_structs - .iter() - .filter(|typ| matches!(typ, TypeMeta::Struct { name, .. } if counts[name] == 1)) - .cloned() - .collect::>(); - - let mut root_index = - python::generate_public_index(&root_classes, &root_interfaces, &root_enums); - root_index.push_str( - python::generate_public_struct_index(&root_structs) - .strip_prefix(GENERATED_PYTHON_HEADER) - .unwrap_or_default(), - ); - write_python_lazy_root_index( - &output_dir.join("__init__.py"), - &root_index, - append, - &suppressed_root_names, - )?; - if pyi { - let mut root_stub = - python_stub::generate_public_index_stub(&root_classes, &root_interfaces, &root_enums); - root_stub.push_str( - python_stub::generate_public_struct_index_stub(&root_structs) - .strip_prefix(GENERATED_PYTHON_HEADER) - .unwrap_or_default(), - ); - write_python_index( - &output_dir.join("__init__.pyi"), - &root_stub, - append, - &suppressed_root_names, - )?; - write_file(&output_dir.join("py.typed"), "")?; - } + let content = serde_json::to_string_pretty(&update.manifest) + .map_err(|error| format!("Failed to serialize COM generation manifest: {error}"))?; + ensure_safe_generated_destination(output_dir, &path)?; + fs::write(&path, format!("{content}\n")) + .map_err(|error| format!("Failed to write {}: {error}", path.display())) +} - let mut groups = BTreeMap::::new(); - for class in classes { - groups - .entry(class.namespace.clone()) - .or_default() - .classes - .push(class.clone()); - } - for interface in interfaces { - groups - .entry(interface.namespace.clone()) - .or_default() - .interfaces - .push(interface.clone()); - } - for typ in enums { - if let TypeMeta::Enum { namespace, .. } = typ { - groups - .entry(namespace.clone()) - .or_default() - .enums - .push(typ.clone()); +fn write_com_js_barrel(com_output_dir: &Path) -> Result<(), String> { + let output_dir = com_output_dir.parent().unwrap_or(com_output_dir); + ensure_safe_generated_parent(output_dir, &com_output_dir.join(".dynwinrt-write-check"))?; + let mut modules: BTreeMap> = BTreeMap::new(); + let mut contents: BTreeMap = BTreeMap::new(); + let entries = fs::read_dir(com_output_dir).map_err(|error| { + format!( + "Failed to read COM output directory {}: {error}", + com_output_dir.display() + ) + })?; + for entry in entries.flatten() { + let path = entry.path(); + let Some(file_name) = path.file_name().and_then(|name| name.to_str()) else { + continue; + }; + let Some(module) = file_name.strip_suffix(".js") else { + continue; + }; + if module == "index" { + continue; } - } - for typ in current_structs { - if let TypeMeta::Struct { namespace, .. } = &typ { - groups - .entry(namespace.clone()) - .or_default() - .structs - .push(typ); + let content = fs::read_to_string(&path) + .map_err(|error| format!("Failed to read {}: {error}", path.display()))?; + let exports = collect_com_cjs_exports(&content); + if !exports.is_empty() { + modules.insert(module.to_string(), exports); + contents.insert(module.to_string(), content); } } + deduplicate_com_barrel_exports(&mut modules, &contents)?; - for (namespace, group) in groups { - write_python_namespace_group(output_dir, &namespace, &group, pyi, append)?; + let mut index = String::from("// Generated by dynwinrt-codegen - do not edit\n"); + for (module, exports) in &modules { + index.push_str(&format!( + "export {{ {} }} from './{module}.js';\n", + exports.iter().cloned().collect::>().join(", ") + )); } - write_python_type_inventory(output_dir, &all_types)?; + let cjs_index = typescript::esm_index_to_cjs_getter(&index); + let esm_index = typescript::esm_index_to_esm(&index); + let index_js = com_output_dir.join("index.js"); + let index_mjs = com_output_dir.join("index.mjs"); + let index_dts = com_output_dir.join("index.d.ts"); + let package_json = com_output_dir.join("package.json"); + for path in [&index_js, &index_mjs, &index_dts, &package_json] { + ensure_safe_generated_destination(output_dir, path)?; + } + fs::write(&index_js, &cjs_index) + .map_err(|error| format!("Failed to write COM index.js: {error}"))?; + fs::write(&index_mjs, &esm_index) + .map_err(|error| format!("Failed to write COM index.mjs: {error}"))?; + fs::write(&index_dts, &index) + .map_err(|error| format!("Failed to write COM index.d.ts: {error}"))?; + + let package = "{\n \"type\": \"commonjs\",\n \"sideEffects\": false\n}\n"; + fs::write(&package_json, package) + .map_err(|error| format!("Failed to write COM package boundary: {error}"))?; Ok(()) } -fn write_python_namespace_group( - output_dir: &Path, - namespace: &str, - group: &PythonNamespaceGroup, - pyi: bool, - append: bool, +fn deduplicate_com_barrel_exports( + modules: &mut BTreeMap>, + contents: &BTreeMap, ) -> Result<(), String> { - use dynwinrt_codegen::codegen::python_stub; - - let segments = python::python_namespace_segments(namespace); - if segments.is_empty() { - return Ok(()); - } - let mut package_dir = output_dir.to_path_buf(); - for segment in &segments { - package_dir.push(segment); - fs::create_dir_all(&package_dir) - .map_err(|e| format!("Failed to create {}: {}", package_dir.display(), e))?; - let runtime_init = package_dir.join("__init__.py"); - if !runtime_init.exists() { - write_file(&runtime_init, GENERATED_PYTHON_HEADER)?; - } - if pyi { - let stub_init = package_dir.join("__init__.pyi"); - if !stub_init.exists() { - write_file(&stub_init, GENERATED_PYTHON_HEADER)?; + let mut owners = BTreeMap::)>::new(); + for (module, exports) in modules.iter_mut() { + let content = &contents[module]; + let names = exports.iter().cloned().collect::>(); + for name in names { + let signature = native_pod_factory_signature(content, &name); + if let Some((owner, owner_signature)) = owners.get(&name) { + if signature.is_some() && signature.as_ref() == owner_signature.as_ref() { + exports.remove(&name); + } else { + return Err(format!( + "COM barrel export `{name}` is ambiguous between `{owner}.js` and `{module}.js`" + )); + } + } else { + owners.insert(name, (module.clone(), signature)); } } } + Ok(()) +} - let mut runtime_exports = Vec::new(); - let mut stub_exports = Vec::new(); - let mut seen = HashSet::new(); - - for class in &group.classes { - if !seen.insert(class.name.clone()) { - continue; - } - let runtime = python::generate_index(std::slice::from_ref(class), &[], &[]); - write_python_facade( - &package_dir, - &segments, - &class.name, - &runtime, - "py", - &mut runtime_exports, - )?; - if pyi { - let stub = python_stub::generate_index_stub(std::slice::from_ref(class), &[], &[]); - write_python_facade( - &package_dir, - &segments, - &class.name, - &stub, - "pyi", - &mut stub_exports, +fn native_pod_factory_signature(content: &str, export_name: &str) -> Option { + let pod_name = export_name.strip_prefix("create")?; + if pod_name.is_empty() { + return None; + } + let pod_name = pod_name.strip_suffix("Array").unwrap_or(pod_name); + [ + format!("const _nativeLayout_{pod_name} = "), + format!("const _nativeUnionLayout_{pod_name} = "), + ] + .into_iter() + .find_map(|prefix| { + content + .lines() + .find(|line| line.starts_with(&prefix)) + .map(str::to_string) + }) +} + +fn finalize_com_generation(output_dir: &Path) -> Result<(), String> { + if !has_winrt_root(output_dir) { + write_com_root_compatibility_barrels(output_dir)?; + } + write_bindings_manifest(output_dir) +} + +fn write_com_root_compatibility_barrels(output_dir: &Path) -> Result<(), String> { + let com_dir = output_dir.join("com"); + let com_js_path = com_dir.join("index.js"); + let com_dts_path = com_dir.join("index.d.ts"); + ensure_safe_generated_destination(output_dir, &com_js_path)?; + ensure_safe_generated_destination(output_dir, &com_dts_path)?; + let com_js = fs::read_to_string(&com_js_path) + .map_err(|error| format!("Failed to read {}: {error}", com_js_path.display()))?; + let com_dts = fs::read_to_string(&com_dts_path) + .map_err(|error| format!("Failed to read {}: {error}", com_dts_path.display()))?; + let root_js = com_js.replace(", './", ", './com/"); + let root_dts = com_dts.replace("from './", "from './com/"); + let index_js = output_dir.join("index.js"); + let index_dts = output_dir.join("index.d.ts"); + ensure_safe_generated_destination(output_dir, &index_js)?; + ensure_safe_generated_destination(output_dir, &index_dts)?; + fs::write(&index_js, &root_js) + .map_err(|error| format!("Failed to write COM compatibility index.js: {error}"))?; + fs::write(&index_dts, root_dts) + .map_err(|error| format!("Failed to write COM compatibility index.d.ts: {error}"))?; + Ok(()) +} + +fn migrate_legacy_com_only_package(output_dir: &Path) -> Result<(), String> { + if has_winrt_root(output_dir) { + return Ok(()); + } + + let package_path = output_dir.join("package.json"); + let index_path = output_dir.join("index.js"); + let index_dts_path = output_dir.join("index.d.ts"); + if !package_path.is_file() || !index_path.is_file() || !index_dts_path.is_file() { + return Ok(()); + } + let package = fs::read_to_string(&package_path) + .map_err(|error| format!("Failed to read {}: {error}", package_path.display()))?; + let index = fs::read_to_string(&index_dts_path) + .map_err(|error| format!("Failed to read {}: {error}", index_dts_path.display()))?; + if !package.contains("\"name\": \"@winapp/bindings\"") + || !(package.contains("\"type\": \"module\"") || package.contains("\"type\": \"commonjs\"")) + || !index.starts_with("// Generated by dynwinrt-codegen") + { + return Ok(()); + } + + let modules = collect_com_index_modules(&index); + if modules.is_empty() { + return Ok(()); + } + + let com_output_dir = output_dir.join("com"); + ensure_safe_generated_parent( + output_dir, + &com_output_dir.join(".dynwinrt-migration-check"), + )?; + for module in modules { + for suffix in [".js", ".d.ts"] { + move_legacy_com_file( + output_dir, + &output_dir.join(format!("{module}{suffix}")), + &com_output_dir.join(format!("{module}{suffix}")), )?; } } - for interface in &group.interfaces { - if !seen.insert(interface.name.clone()) { - continue; - } - let runtime = python::generate_index(&[], std::slice::from_ref(interface), &[]); - write_python_facade( - &package_dir, - &segments, - &interface.name, - &runtime, - "py", - &mut runtime_exports, - )?; - if pyi { - let stub = python_stub::generate_index_stub(&[], std::slice::from_ref(interface), &[]); - write_python_facade( - &package_dir, - &segments, - &interface.name, - &stub, - "pyi", - &mut stub_exports, - )?; - } + + for path in [ + output_dir.join("index.js"), + output_dir.join("index.mjs"), + output_dir.join("index.d.ts"), + package_path, + ] { + if path.exists() { + ensure_safe_generated_destination(output_dir, &path)?; + fs::remove_file(&path) + .map_err(|error| format!("Failed to remove {}: {error}", path.display()))?; + } + } + write_com_js_barrel(&com_output_dir)?; + finalize_com_generation(output_dir) +} + +fn collect_com_index_modules(index: &str) -> BTreeSet { + index + .lines() + .filter_map(|line| { + let (_, module) = line.split_once(" from './")?; + let module = module.strip_suffix(".js';")?; + (!module.is_empty() && !module.contains(['/', '\\'])).then(|| module.to_string()) + }) + .collect() +} + +fn move_legacy_com_file( + output_dir: &Path, + source: &Path, + destination: &Path, +) -> Result<(), String> { + if !source.exists() { + return Ok(()); + } + ensure_safe_generated_destination(output_dir, source)?; + ensure_safe_generated_destination(output_dir, destination)?; + if destination.exists() { + let source_content = fs::read(source) + .map_err(|error| format!("Failed to read {}: {error}", source.display()))?; + let destination_content = fs::read(destination) + .map_err(|error| format!("Failed to read {}: {error}", destination.display()))?; + if source_content != destination_content { + return Err(format!( + "Cannot migrate legacy COM file {} because {} already exists with different content", + source.display(), + destination.display() + )); + } + fs::remove_file(source) + .map_err(|error| format!("Failed to remove {}: {error}", source.display()))?; + return Ok(()); + } + + fs::rename(source, destination).map_err(|error| { + format!( + "Failed to migrate legacy COM file {} to {}: {error}", + source.display(), + destination.display() + ) + }) +} + +fn has_winrt_root(output_dir: &Path) -> bool { + ["index.mjs", "index.proxy.js", "lifetime.js"] + .iter() + .any(|name| output_dir.join(name).is_file()) +} + +fn write_bindings_manifest(output_dir: &Path) -> Result<(), String> { + let has_winrt_root = has_winrt_root(output_dir); + let winrt_subpath_names = if has_winrt_root { + collect_subpath_names_from_dir(output_dir)? + } else { + BTreeSet::new() + }; + let com_subpath_names = collect_com_subpath_names(&output_dir.join("com"))?; + let content = package::render_bindings_package_json(&package::BindingsPackageManifestInput { + has_winrt_root, + winrt_subpath_names: &winrt_subpath_names, + com_subpath_names: &com_subpath_names, + }); + let path = output_dir.join("package.json"); + ensure_safe_generated_destination(output_dir, &path)?; + fs::write(&path, content) + .map_err(|error| format!("Failed to write {}: {error}", path.display())) +} + +fn collect_com_subpath_names(com_output_dir: &Path) -> Result, String> { + let index_path = com_output_dir.join("index.d.ts"); + if !index_path.is_file() { + return Ok(BTreeSet::new()); + } + let index = fs::read_to_string(&index_path) + .map_err(|error| format!("Failed to read {}: {error}", index_path.display()))?; + Ok(collect_com_index_modules(&index)) +} + +fn collect_com_cjs_exports(content: &str) -> BTreeSet { + content + .lines() + .filter_map(|line| { + let line = line.trim_start(); + let rest = line.strip_prefix("exports.")?; + let name = rest + .chars() + .take_while(|character| { + character.is_ascii_alphanumeric() || *character == '_' || *character == '$' + }) + .collect::(); + (!name.is_empty() && rest[name.len()..].trim_start().starts_with('=')).then_some(name) + }) + .collect() +} + +fn write_lifetime_module(output_dir: &Path) -> Result<(), String> { + let js = "'use strict';\n\ +let activeScope = null;\n\ +const trackedScopes = new WeakMap();\n\ +function trackProjectedValue(value, typeName) {\n\ + activeScope?.track(value, typeName);\n\ + return value;\n\ +}\n\ +function isObjectLike(value) {\n\ + return value !== null && (typeof value === 'object' || typeof value === 'function');\n\ +}\n\ +function removeTracking(scope, value) {\n\ + const scopes = trackedScopes.get(value);\n\ + if (!scopes) return;\n\ + scopes.delete(scope);\n\ + if (scopes.size === 0) trackedScopes.delete(value);\n\ +}\n\ +function untrackProjectedValue(value) {\n\ + const scopes = trackedScopes.get(value);\n\ + if (!scopes) return;\n\ + for (const scope of [...scopes]) scope.untrack(value);\n\ +}\n\ +function castProjectedValueOwned(value, iid, typeName) {\n\ + let projected;\n\ + try { projected = value.cast(iid); }\n\ + catch (error) {\n\ + try { value.release(); } catch {}\n\ + throw error;\n\ + }\n\ + if (projected !== value) {\n\ + try { value.release(); }\n\ + catch (error) {\n\ + try { projected.release(); } catch {}\n\ + throw error;\n\ + }\n\ + }\n\ + return trackProjectedValue(projected, typeName);\n\ +}\n\ +function castProjectedValueBorrowed(value, iid, typeName) {\n\ + return trackProjectedValue(value.cast(iid), typeName);\n\ +}\n\ +const castProjectedValue = castProjectedValueOwned;\n\ +function projectAs(value, type) {\n\ + const source = isObjectLike(value) && '_obj' in value ? value._obj : value;\n\ + if (!isObjectLike(source)) throw new TypeError('projectAs requires a projected value or wrapper.');\n\ + if (!isObjectLike(type) || typeof type._fromNativeBorrowed !== 'function') {\n\ + throw new TypeError('projectAs requires a generated runtime class type.');\n\ + }\n\ + const projected = type._fromNativeBorrowed(source);\n\ + if (!isObjectLike(projected) || !('_obj' in projected)) {\n\ + throw new TypeError('The generated runtime class returned an invalid projection.');\n\ + }\n\ + return projected;\n\ +}\n\ +function releaseProjected(value) {\n\ + if (!isObjectLike(value) || !('_obj' in value)) {\n\ + throw new TypeError('releaseProjected requires a generated projected wrapper.');\n\ + }\n\ + const projected = value._obj;\n\ + if (!isObjectLike(projected) || typeof projected.release !== 'function') {\n\ + throw new TypeError('The projected wrapper does not contain a releasable native value.');\n\ + }\n\ + projected.release();\n\ + untrackProjectedValue(projected);\n\ +}\n\ +function createProjectedLifetimeScope() {\n\ + const previousScope = activeScope;\n\ + const registry = new Map();\n\ + let disposed = false;\n\ + const scope = {\n\ + get disposed() { return disposed; },\n\ + track(value, typeName) {\n\ + if (disposed) throw new Error('Cannot track values in a disposed projection scope.');\n\ + if (registry.has(value)) return;\n\ + registry.set(value, typeName);\n\ + let scopes = trackedScopes.get(value);\n\ + if (!scopes) trackedScopes.set(value, scopes = new Set());\n\ + scopes.add(scope);\n\ + },\n\ + untrack(value) {\n\ + registry.delete(value);\n\ + removeTracking(scope, value);\n\ + },\n\ + dispose() {\n\ + if (disposed) return;\n\ + if (activeScope !== scope) throw new Error('Projection lifetime scopes must be disposed in LIFO order.');\n\ + let firstError;\n\ + for (const [value] of [...registry].reverse()) {\n\ + try { value.release(); scope.untrack(value); }\n\ + catch (error) { firstError ??= error; }\n\ + }\n\ + if (firstError !== undefined) throw firstError;\n\ + disposed = true;\n\ + activeScope = previousScope;\n\ + },\n\ + };\n\ + activeScope = scope;\n\ + return scope;\n\ +}\n\ +exports.trackProjectedValue = trackProjectedValue;\n\ +exports.castProjectedValue = castProjectedValue;\n\ +exports.castProjectedValueOwned = castProjectedValueOwned;\n\ +exports.castProjectedValueBorrowed = castProjectedValueBorrowed;\n\ +exports.projectAs = projectAs;\n\ +exports.releaseProjected = releaseProjected;\n\ +exports.createProjectedLifetimeScope = createProjectedLifetimeScope;\n"; + let dts = "export declare function trackProjectedValue(value: T, typeName: string): T;\n\ +export declare function castProjectedValue(value: T, iid: unknown, typeName: string): T;\n\ +export declare function castProjectedValueOwned(value: T, iid: unknown, typeName: string): T;\n\ +export declare function castProjectedValueBorrowed(value: T, iid: unknown, typeName: string): T;\n\ +export interface ProjectedType {\n\ + readonly prototype: T;\n\ +}\n\ +/**\n\ + * Borrows a raw projected value or wrapper and exposes it as a generated type.\n\ + * The input remains valid; the returned projection owns its interface view and\n\ + * must be released independently or retained by a projected lifetime scope.\n\ + */\n\ +export declare function projectAs(value: unknown, type: ProjectedType): T;\n\ +export declare function releaseProjected(value: object): void;\n\ +export interface ProjectedLifetimeScope {\n\ + readonly disposed: boolean;\n\ + dispose(): void;\n\ +}\n\ +export declare function createProjectedLifetimeScope(): ProjectedLifetimeScope;\n"; + let js_path = output_dir.join("lifetime.js"); + let dts_path = output_dir.join("lifetime.d.ts"); + ensure_safe_generated_destination(output_dir, &js_path)?; + ensure_safe_generated_destination(output_dir, &dts_path)?; + fs::write(&js_path, js).map_err(|e| format!("Failed to write lifetime.js: {e}"))?; + fs::write(&dts_path, dts).map_err(|e| format!("Failed to write lifetime.d.ts: {e}"))?; + Ok(()) +} + +fn render_index_from_existing_js_files(output_dir: &Path) -> Result { + let mut out = String::from("// Generated by dynwinrt-codegen \u{2014} do not edit\n"); + let records = read_javascript_type_inventory(output_dir)?.records; + let _layout = javascript::install_javascript_module_layout_with_records( + records.iter().map(|record| record.identity.clone()), + records.iter().cloned(), + )?; + let mut targets = javascript::javascript_output_targets(); + targets.sort_by(|left, right| left.canonical_module.cmp(&right.canonical_module)); + let primary_owners = targets + .iter() + .map(|target| { + ( + target.projected_name.clone(), + target.canonical_module.clone(), + ) + }) + .collect::>(); + let mut candidates: Vec<(String, Vec)> = Vec::new(); + for target in targets { + let path = output_dir.join(format!("{}.js", target.canonical_module)); + if !path.is_file() { + continue; + } + let content = fs::read_to_string(&path) + .map_err(|error| format!("Failed to read {}: {error}", path.display()))?; + let mut names = collect_public_exports_from_js(&content); + if target.collides { + names.retain(|name| name != &target.identity.name); + } + names.retain(|name| !target.compatibility_aliases.contains(name)); + names.sort(); + names.dedup(); + if names.is_empty() { + continue; + } + candidates.push((target.canonical_module, names)); + } + let lifetime_path = output_dir.join("lifetime.js"); + if lifetime_path.is_file() { + let lifetime = fs::read_to_string(&lifetime_path) + .map_err(|error| format!("Failed to read {}: {error}", lifetime_path.display()))?; + let mut names = collect_public_exports_from_js(&lifetime); + names.sort(); + names.dedup(); + if !names.is_empty() { + candidates.push(("lifetime".into(), names)); + } + } + let mut seen_exports: BTreeSet = BTreeSet::new(); + let mut modules: Vec<(String, Vec)> = Vec::new(); + for (module, names) in candidates { + let filtered: Vec = names + .into_iter() + .filter(|name| { + if primary_owners + .get(name) + .is_some_and(|owner| owner != &module) + { + return false; + } + seen_exports.insert(name.clone()) + }) + .collect(); + if filtered.is_empty() { + continue; + } + modules.push((module, filtered)); + } + for (module, names) in modules { + out.push_str(&format!( + "export {{ {} }} from './{}.js';\n", + names.join(", "), + module + )); + } + Ok(out) +} + +fn collect_public_exports_from_js(content: &str) -> Vec { + let mut names = Vec::new(); + for line in content.lines() { + let line = line.trim_start(); + let Some(rest) = line.strip_prefix("exports.") else { + continue; + }; + let name: String = rest + .chars() + .take_while(|c| c.is_ascii_alphanumeric() || *c == '_' || *c == '$') + .collect(); + if name.is_empty() { + continue; + } + // Keep IIDs, parameter type arrays, and struct type descriptors scoped + // to their per-type modules. Root barrels should expose user-facing + // classes, enums, pack/unpack helpers, and interfaces only. + if name == "trackProjectedValue" + || name == "castProjectedValue" + || name == "castProjectedValueOwned" + || name == "castProjectedValueBorrowed" + || name.starts_with("__") + || name.starts_with("IID_") + || name.ends_with("_PARAM_TYPES") + || name.ends_with("_Type") + { + continue; + } + names.push(name); + } + names +} + +/// Enumerate generated `.js` modules recursively and return package subpaths +/// without extensions. Excludes root/nested barrels and the domain-specific +/// Classic COM tree, which is added separately. +fn collect_subpath_names_from_dir(output_dir: &Path) -> Result, String> { + const BARREL_STEMS: &[&str] = &["index", "index.getter", "index.proxy"]; + if output_dir.join(JAVASCRIPT_TYPE_INVENTORY).is_file() { + let records = read_javascript_type_inventory(output_dir)?.records; + let _layout = javascript::install_javascript_module_layout_with_records( + records.iter().map(|record| record.identity.clone()), + records.iter().cloned(), + )?; + let mut names = javascript::javascript_output_targets() + .into_iter() + .map(|target| target.canonical_module) + .collect::>(); + if output_dir.join("lifetime.js").is_file() { + names.insert("lifetime".into()); + } + return Ok(names); + } + + // Legacy flat output has no identity inventory. Only inspect generated + // root files; never recurse into an application tree or dependencies when + // `--output .` is used. + let mut names = BTreeSet::new(); + let entries = fs::read_dir(output_dir) + .map_err(|error| format!("Failed to read {}: {error}", output_dir.display()))?; + for entry in entries { + let entry = entry.map_err(|error| format!("Failed to read directory entry: {error}"))?; + let path = entry.path(); + let metadata = fs::symlink_metadata(&path) + .map_err(|error| format!("Failed to inspect {}: {error}", path.display()))?; + if is_link_or_reparse_point(&metadata) || !metadata.is_file() { + continue; + } + let Some(fname) = path.file_name().and_then(|name| name.to_str()) else { + continue; + }; + let Some(stem) = fname.strip_suffix(".js") else { + continue; + }; + if BARREL_STEMS.iter().any(|barrel| stem == *barrel) { + continue; + } + let generated = fs::read_to_string(&path) + .map(|content| content.starts_with("// Generated by dynwinrt-codegen")) + .unwrap_or(false); + if generated || stem == "lifetime" { + names.insert(stem.into()); + } + } + Ok(names) +} + +fn strip_broken_imports(output_dir: &Path) -> Result<(), String> { + use dynwinrt_codegen::codegen::project::get_import_name; + + // If `--import-name ./runtime.js` was used, that stem is not one of the + // emitted modules but must not be stripped. + let runtime_name = get_import_name(); + let runtime_stem = (runtime_name.starts_with("./") || runtime_name.starts_with("../")) + .then(|| { + Path::new(&runtime_name) + .file_stem() + .and_then(|stem| stem.to_str()) + .map(str::to_string) + }) + .flatten(); + + let target_exists = |source: &Path, target: &str| { + let target_stem = target.rsplit('/').next().unwrap_or(target); + if target_stem == "lifetime" || runtime_stem.as_deref() == Some(target_stem) { + return true; + } + source + .parent() + .unwrap_or(output_dir) + .join(format!("{target}.js")) + .is_file() + }; + + // Three patterns to strip when the target sibling doesn't exist: + // + // 1. Legacy ESM import (in case render_esm output leaks through): + // import { X } from './Foo.js'; + // + // 2. CJS lazy loader triplet emitted by convert_to_cjs_with_lazy (class files): + // let __m_Foo; + // const __load_Foo = () => (__m_Foo ??= require('./Foo.js')); + // const X = __lazy(__load_Foo, 'X'); // one per imported symbol + // + // 3. Index-level lazy exports emitted by esm_index_to_cjs_lazy: + // exports.X = undefined; + // Object.defineProperty(exports, 'X', { ... get() { return require('./Foo.js').X; } }); + // Both lines reference the same missing target and must go together. + let esm_import_re = + regex::Regex::new(r#"(?m)^import \{[^}]*\} from '((?:\./|\.\./)[^']+)\.js';\r?\n"#) + .map_err(|e| format!("regex error: {}", e))?; + + // Class-file lazy loader block. New shape: + // let __m_Foo; + // const __load_Foo = () => (__m_Foo ??= require('./Foo.js')); + // const __get_X = () => __load_Foo().X; // one per imported symbol + let cjs_lazy_re = regex::Regex::new( + r"(?ms)^let __m_[A-Za-z0-9_]+;\r?\nconst __load_[A-Za-z0-9_]+ = \(\) => \(__m_[A-Za-z0-9_]+ \?\?= require\('((?:\./|\.\./)[^']+)\.js'\)\);\r?\n(?:const __get_[A-Za-z0-9_]+ = \(\) => __load_[A-Za-z0-9_]+\(\)\.[A-Za-z0-9_]+;\r?\n)*", + ) + .map_err(|e| format!("regex error: {}", e))?; + + // Class-file eager destructured require: + // const { IID_X, X_PARAM_TYPES } = require('./Foo.js'); + // Emitted alongside the lazy block for symbols the native runtime needs + // as concrete values (IIDs, DynWinRtType arrays, struct type descriptors). + let cjs_eager_re = + regex::Regex::new(r"(?m)^const \{[^}]+\} = require\('((?:\./|\.\./)[^']+)\.js'\);\r?\n") + .map_err(|e| format!("regex error: {}", e))?; + + // Index-file lazy export line emitted by `esm_index_to_cjs_lazy`: + // { let _m; exports.NAME = __lazy(() => (_m ??= require('./Foo.js')).NAME); } + // captures the module basename in group 1. + let index_dp_re = regex::Regex::new( + r"(?m)^\{ let _m; exports\.[A-Za-z0-9_]+ = __lazy\(\(\) => \(_m \?\?= require\('((?:\./|\.\./)[^']+)\.js'\)\)\.[A-Za-z0-9_]+\); \}\r?\n", + ) + .map_err(|e| format!("regex error: {}", e))?; + + let javascript_files = javascript::javascript_output_targets() + .into_iter() + .map(|target| output_dir.join(format!("{}.js", target.canonical_module))) + .filter(|path| path.is_file()) + .collect::>(); + for path in javascript_files { + ensure_safe_generated_destination(output_dir, &path)?; + let content = match fs::read_to_string(&path) { + Ok(c) => c, + Err(_) => continue, + }; + if !content.starts_with("// Generated by dynwinrt-codegen") { + continue; + } + let mut changed = false; + + // 1. CJS lazy loaders for missing targets (class files). + let filtered = cjs_lazy_re.replace_all(&content, |caps: ®ex::Captures| { + let target = &caps[1]; + if target_exists(&path, target) { + caps[0].to_string() + } else { + changed = true; + String::new() + } + }); + + // 1b. CJS eager destructured requires for missing sibling modules. + let filtered = cjs_eager_re.replace_all(&filtered, |caps: ®ex::Captures| { + let target = &caps[1]; + if target_exists(&path, target) { + caps[0].to_string() + } else { + changed = true; + String::new() + } + }); + + // 2. Index lazy-export lines. The new form has a single `{ let _m; ... }` + // block per export; captures the module basename. + let filtered = index_dp_re.replace_all(&filtered, |caps: ®ex::Captures| { + let target = &caps[1]; + if target_exists(&path, target) { + caps[0].to_string() + } else { + changed = true; + String::new() + } + }); + + // 3. Legacy ESM imports (defence-in-depth if pipeline ever emits ESM). + let filtered = esm_import_re.replace_all(&filtered, |caps: ®ex::Captures| { + let target = &caps[1]; + if target_exists(&path, target) { + caps[0].to_string() + } else { + changed = true; + String::new() + } + }); + if changed { + ensure_safe_generated_destination(output_dir, &path)?; + fs::write(&path, filtered.as_bytes()) + .map_err(|e| format!("Failed to write {}: {}", path.display(), e))?; + } + } + Ok(()) +} + +fn generate_py_files( + output_dir: &Path, + all_classes: &[meta::ClassMeta], + all_interfaces: &[meta::InterfaceMeta], + all_enums: &[TypeMeta], + shared_interfaces: &[meta::InterfaceMeta], + known_types: &HashSet, + delegate_type_names: &HashSet, + shared_iids: &HashSet, + pyi: bool, +) -> Result<(), String> { + use dynwinrt_codegen::codegen::python_stub; + + write_file( + &output_dir.join("_runtime.py"), + &python::generate_runtime_support_module(), + )?; + if pyi { + write_file( + &output_dir.join("_runtime.pyi"), + &python_stub::generate_runtime_support_stub(), + )?; + write_file( + &output_dir.join("_typing.pyi"), + &python_stub::generate_typing_support_module(), + )?; + } + + let mut generated_modules = HashSet::new(); + let mut struct_interfaces = all_interfaces.to_vec(); + struct_interfaces.extend_from_slice(shared_interfaces); + let structs = python::package_structs(all_classes, &struct_interfaces); + + // A runtime class owns its public identity when metadata also exposes an + // interface or enum with the same namespace/name. Generate in precedence + // order and render each final module exactly once. + for class in all_classes { + let module = python::python_module_name(&class.namespace, &class.name); + if !generated_modules.insert(module.clone()) { + continue; + } + let code = python::generate_class(class, known_types, delegate_type_names, shared_iids); + let filepath = output_dir.join(format!("{module}.py")); + write_file(&filepath, &code)?; + println!("Generated {}", filepath.display()); + if pyi { + let stub = python_stub::generate_class_stub( + class, + known_types, + delegate_type_names, + shared_iids, + ); + write_file(&output_dir.join(format!("{module}.pyi")), &stub)?; + } + } + for en in all_enums { + if let TypeMeta::Enum { + namespace, name, .. + } = en + { + let module = python::python_module_name(namespace, name); + if !generated_modules.insert(module.clone()) { + continue; + } + if let Some(code) = python::generate_enum(en) { + let filepath = output_dir.join(format!("{module}.py")); + write_file(&filepath, &code)?; + println!("Generated {}", filepath.display()); + } + if pyi { + if let Some(stub) = python_stub::generate_enum_stub(en) { + let p = output_dir.join(format!("{module}.pyi")); + write_file(&p, &stub)?; + } + } + } + } + for iface in all_interfaces.iter().chain(shared_interfaces) { + let module = python::python_module_name(&iface.namespace, &iface.name); + if !generated_modules.insert(module.clone()) { + continue; + } + let code = python::generate_interface(iface, known_types, delegate_type_names); + let filepath = output_dir.join(format!("{module}.py")); + write_file(&filepath, &code)?; + println!("Generated {}", filepath.display()); + if pyi { + let stub = + python_stub::generate_interface_stub(iface, known_types, delegate_type_names); + write_file(&output_dir.join(format!("{module}.pyi")), &stub)?; + } + } + for typ in &structs { + let TypeMeta::Struct { + namespace, name, .. + } = typ + else { + continue; + }; + let module = python::python_module_name(namespace, name); + if !generated_modules.insert(module.clone()) { + return Err(format!( + "Python struct module `{namespace}.{name}` collides with another generated type" + )); + } + if let Some(code) = python::generate_struct(typ) { + let filepath = output_dir.join(format!("{module}.py")); + write_file(&filepath, &code)?; + println!("Generated {}", filepath.display()); + } + if pyi { + if let Some(stub) = python_stub::generate_struct_stub(typ) { + write_file(&output_dir.join(format!("{module}.pyi")), &stub)?; + } + } + } + if pyi { + let marker = output_dir.join("py.typed"); + write_file(&marker, "")?; + } + Ok(()) +} + +#[derive(Default)] +struct PythonNamespaceGroup { + classes: Vec, + interfaces: Vec, + enums: Vec, + structs: Vec, +} + +#[derive(Clone, Debug, Eq, Hash, PartialEq)] +struct PythonGeneratedType { + kind: String, + identity: python::PythonTypeIdentity, +} + +fn write_python_package_indexes( + output_dir: &Path, + classes: &[meta::ClassMeta], + interfaces: &[meta::InterfaceMeta], + enums: &[TypeMeta], + pyi: bool, + append: bool, +) -> Result<(), String> { + use dynwinrt_codegen::codegen::python_stub; + + let current_structs = python::package_structs(classes, interfaces); + let current_types = python_generated_types(classes, interfaces, enums); + let mut all_types = if append { + read_python_type_inventory(output_dir)? + } else { + Vec::new() + }; + all_types.extend(current_types); + let mut seen_types = HashSet::new(); + all_types.retain(|typ| seen_types.insert(typ.clone())); + + let module_identities = all_types + .iter() + .map(|typ| typ.identity.clone()) + .collect::>(); + let _layout = python::install_python_module_layout(module_identities.clone())?; + validate_python_public_identities(&module_identities)?; + + let mut interface_counts = HashMap::::new(); + for typ in &all_types { + if typ.kind == "interface" { + *interface_counts + .entry(typ.identity.name.clone()) + .or_default() += 1; + } + } + if let Some((name, _)) = interface_counts.iter().find(|(_, count)| **count > 1) { + return Err(format!( + "Python generation cannot safely project multiple interfaces named `{name}`; \ + their delegate and generic runtime symbols are ambiguous" + )); + } + + let mut counts = HashMap::::new(); + for typ in &all_types { + *counts.entry(typ.identity.name.clone()).or_default() += 1; + } + let suppressed_root_names = counts + .iter() + .filter(|(_, count)| **count > 1) + .map(|(name, _)| name.clone()) + .collect::>(); + let root_classes = classes + .iter() + .filter(|class| counts[&class.name] == 1) + .cloned() + .collect::>(); + let root_interfaces = interfaces + .iter() + .filter(|interface| counts[&interface.name] == 1) + .cloned() + .collect::>(); + let root_enums = enums + .iter() + .filter(|typ| matches!(typ, TypeMeta::Enum { name, .. } if counts[name] == 1)) + .cloned() + .collect::>(); + let root_structs = current_structs + .iter() + .filter(|typ| matches!(typ, TypeMeta::Struct { name, .. } if counts[name] == 1)) + .cloned() + .collect::>(); + + let mut root_index = + python::generate_public_index(&root_classes, &root_interfaces, &root_enums); + root_index.push_str( + python::generate_public_struct_index(&root_structs) + .strip_prefix(GENERATED_PYTHON_HEADER) + .unwrap_or_default(), + ); + write_python_lazy_root_index( + &output_dir.join("__init__.py"), + &root_index, + append, + &suppressed_root_names, + )?; + if pyi { + let mut root_stub = + python_stub::generate_public_index_stub(&root_classes, &root_interfaces, &root_enums); + root_stub.push_str( + python_stub::generate_public_struct_index_stub(&root_structs) + .strip_prefix(GENERATED_PYTHON_HEADER) + .unwrap_or_default(), + ); + write_python_index( + &output_dir.join("__init__.pyi"), + &root_stub, + append, + &suppressed_root_names, + )?; + write_file(&output_dir.join("py.typed"), "")?; + } + + let mut groups = BTreeMap::::new(); + for class in classes { + groups + .entry(class.namespace.clone()) + .or_default() + .classes + .push(class.clone()); + } + for interface in interfaces { + groups + .entry(interface.namespace.clone()) + .or_default() + .interfaces + .push(interface.clone()); + } + for typ in enums { + if let TypeMeta::Enum { namespace, .. } = typ { + groups + .entry(namespace.clone()) + .or_default() + .enums + .push(typ.clone()); + } + } + for typ in current_structs { + if let TypeMeta::Struct { namespace, .. } = &typ { + groups + .entry(namespace.clone()) + .or_default() + .structs + .push(typ); + } + } + + for (namespace, group) in groups { + write_python_namespace_group(output_dir, &namespace, &group, pyi, append)?; + } + write_python_type_inventory(output_dir, &all_types)?; + Ok(()) +} + +fn write_python_namespace_group( + output_dir: &Path, + namespace: &str, + group: &PythonNamespaceGroup, + pyi: bool, + append: bool, +) -> Result<(), String> { + use dynwinrt_codegen::codegen::python_stub; + + let segments = python::python_namespace_segments(namespace); + if segments.is_empty() { + return Ok(()); + } + let mut package_dir = output_dir.to_path_buf(); + for segment in &segments { + package_dir.push(segment); + fs::create_dir_all(&package_dir) + .map_err(|e| format!("Failed to create {}: {}", package_dir.display(), e))?; + let runtime_init = package_dir.join("__init__.py"); + if !runtime_init.exists() { + write_file(&runtime_init, GENERATED_PYTHON_HEADER)?; + } + if pyi { + let stub_init = package_dir.join("__init__.pyi"); + if !stub_init.exists() { + write_file(&stub_init, GENERATED_PYTHON_HEADER)?; + } + } + } + + let mut runtime_exports = Vec::new(); + let mut stub_exports = Vec::new(); + let mut seen = HashSet::new(); + + for class in &group.classes { + if !seen.insert(class.name.clone()) { + continue; + } + let runtime = python::generate_index(std::slice::from_ref(class), &[], &[]); + write_python_facade( + &package_dir, + &segments, + &class.name, + &runtime, + "py", + &mut runtime_exports, + )?; + if pyi { + let stub = python_stub::generate_index_stub(std::slice::from_ref(class), &[], &[]); + write_python_facade( + &package_dir, + &segments, + &class.name, + &stub, + "pyi", + &mut stub_exports, + )?; + } + } + for interface in &group.interfaces { + if !seen.insert(interface.name.clone()) { + continue; + } + let runtime = python::generate_index(&[], std::slice::from_ref(interface), &[]); + write_python_facade( + &package_dir, + &segments, + &interface.name, + &runtime, + "py", + &mut runtime_exports, + )?; + if pyi { + let stub = python_stub::generate_index_stub(&[], std::slice::from_ref(interface), &[]); + write_python_facade( + &package_dir, + &segments, + &interface.name, + &stub, + "pyi", + &mut stub_exports, + )?; + } + } + for typ in &group.enums { + let TypeMeta::Enum { name, .. } = typ else { + continue; + }; + if !seen.insert(name.clone()) { + continue; + } + let runtime = python::generate_index(&[], &[], std::slice::from_ref(typ)); + write_python_facade( + &package_dir, + &segments, + name, + &runtime, + "py", + &mut runtime_exports, + )?; + if pyi { + let stub = python_stub::generate_index_stub(&[], &[], std::slice::from_ref(typ)); + write_python_facade( + &package_dir, + &segments, + name, + &stub, + "pyi", + &mut stub_exports, + )?; + } + } + for typ in &group.structs { + let TypeMeta::Struct { name, .. } = typ else { + continue; + }; + if !seen.insert(name.clone()) { + continue; + } + let runtime = python::generate_struct_index(std::slice::from_ref(typ)); + if runtime.lines().any(|line| line.starts_with("from .")) { + write_python_facade( + &package_dir, + &segments, + name, + &runtime, + "py", + &mut runtime_exports, + )?; + } + if pyi { + let stub = python_stub::generate_struct_index_stub(std::slice::from_ref(typ)); + if stub.lines().any(|line| line.starts_with("from .")) { + write_python_facade( + &package_dir, + &segments, + name, + &stub, + "pyi", + &mut stub_exports, + )?; + } + } + } + + let runtime_index = format!("{}{}", GENERATED_PYTHON_HEADER, runtime_exports.join("\n")); + let suppressed_root_names = HashSet::new(); + write_python_lazy_root_index( + &package_dir.join("__init__.py"), + &runtime_index, + append, + &suppressed_root_names, + )?; + if pyi { + let stub_index = format!("{}{}", GENERATED_PYTHON_HEADER, stub_exports.join("\n")); + write_python_index( + &package_dir.join("__init__.pyi"), + &stub_index, + append, + &suppressed_root_names, + )?; + } + Ok(()) +} + +fn write_python_facade( + package_dir: &Path, + namespace_segments: &[String], + type_name: &str, + implementation_index: &str, + extension: &str, + package_exports: &mut Vec, +) -> Result<(), String> { + let import_line = implementation_index + .lines() + .find(|line| line.starts_with("from .")) + .ok_or_else(|| format!("Generated index for `{type_name}` has no import"))?; + let (source, exports) = import_line + .strip_prefix("from .") + .and_then(|line| line.split_once(" import ")) + .ok_or_else(|| format!("Generated index import for `{type_name}` is invalid"))?; + let exports = exports.split('#').next().unwrap_or(exports).trim(); + let exported_type = exports.split(',').any(|export| { + export + .trim() + .split_once(" as ") + .map_or_else(|| export.trim(), |(_, alias)| alias.trim()) + == type_name + }); + let exports = if extension == "pyi" { + exports + .split(',') + .map(|export| { + let export = export.trim(); + if export.contains(" as ") { + export.to_string() + } else { + format!("{export} as {export}") + } + }) + .collect::>() + .join(", ") + } else { + exports.to_string() + }; + let relative_root = ".".repeat(namespace_segments.len() + 1); + let mut facade = + format!("{GENERATED_PYTHON_HEADER}from {relative_root}{source} import {exports}\n"); + if extension == "py" && exported_type { + facade.push_str(&format!("\n{type_name}.__module__ = __name__\n")); + } + let public_module = python::python_public_module_name(type_name); + write_file( + &package_dir.join(format!("{public_module}.{extension}")), + &facade, + )?; + if exported_type { + let package_export = if extension == "pyi" { + format!("from .{public_module} import {type_name} as {type_name}") + } else { + format!("from .{public_module} import {type_name}") + }; + package_exports.push(package_export); + } + Ok(()) +} + +fn write_python_index( + path: &Path, + generated: &str, + append: bool, + suppressed_names: &HashSet, +) -> Result<(), String> { + let content = if append && path.exists() { + let existing = fs::read_to_string(path) + .map_err(|e| format!("Failed to read {}: {}", path.display(), e))?; + merge_python_indexes(&existing, generated, suppressed_names) + } else { + merge_python_indexes(GENERATED_PYTHON_HEADER, generated, suppressed_names) + }; + write_file(path, &content) +} + +fn write_python_lazy_root_index( + path: &Path, + generated: &str, + append: bool, + suppressed_names: &HashSet, +) -> Result<(), String> { + let existing = if append && path.exists() { + fs::read_to_string(path).map_err(|e| format!("Failed to read {}: {}", path.display(), e))? + } else { + GENERATED_PYTHON_HEADER.to_string() + }; + let content = merge_python_lazy_root_indexes(&existing, generated, suppressed_names); + write_file(path, &content) +} + +fn merge_python_lazy_root_indexes( + existing: &str, + generated: &str, + suppressed_names: &HashSet, +) -> String { + let mut exports = BTreeMap::::new(); + collect_python_root_exports(existing, suppressed_names, &mut exports); + collect_python_root_exports(generated, suppressed_names, &mut exports); + + let mut out = String::from(GENERATED_PYTHON_HEADER); + out.push_str("from importlib import import_module as _import_module\n\n"); + out.push_str("__all__ = (\n"); + for name in exports.keys() { + out.push_str(&format!(" \"{name}\",\n")); + } + out.push_str(")\n\n"); + out.push_str("_EXPORTS = {\n"); + for (name, (module, symbol)) in &exports { + out.push_str(&format!(" \"{name}\": (\"{module}\", \"{symbol}\"),\n")); + } + out.push_str( + "}\n\n\ + \n\ + def __getattr__(name):\n\ + \x20 try:\n\ + \x20 module_name, symbol_name = _EXPORTS[name]\n\ + \x20 except KeyError:\n\ + \x20 raise AttributeError(\n\ + \x20 f\"module {__name__!r} has no attribute {name!r}\"\n\ + \x20 ) from None\n\ + \x20 value = getattr(_import_module(module_name, __name__), symbol_name)\n\ + \x20 globals()[name] = value\n\ + \x20 return value\n\ + \n\ + \n\ + def __dir__():\n\ + \x20 return sorted(set(globals()) | set(__all__))\n", + ); + out +} + +fn collect_python_root_exports( + content: &str, + suppressed_names: &HashSet, + exports: &mut BTreeMap, +) { + for line in content.lines() { + if let Some((module, symbols)) = parse_python_import_line(line) { + for (source_symbol, exported_symbol) in symbols { + if suppressed_names.contains(&source_symbol) + || suppressed_names.contains(&exported_symbol) + { + continue; + } + exports + .entry(exported_symbol) + .or_insert_with(|| (module.clone(), source_symbol)); + } + } else if let Some((exported_symbol, module, source_symbol)) = + parse_python_lazy_export(line) + { + if suppressed_names.contains(&source_symbol) + || suppressed_names.contains(&exported_symbol) + { + continue; + } + exports + .entry(exported_symbol) + .or_insert((module, source_symbol)); + } + } +} + +fn parse_python_import_line(line: &str) -> Option<(String, Vec<(String, String)>)> { + let line = line.split_once(" #").map_or(line, |(line, _)| line); + let (source, exports) = line.split_once(" import ")?; + let module = source.strip_prefix("from ")?.to_string(); + if !module.starts_with('.') { + return None; + } + let exports = exports + .split(',') + .map(str::trim) + .filter(|export| !export.is_empty()) + .map(|export| { + export.split_once(" as ").map_or_else( + || (export.to_string(), export.to_string()), + |(source, alias)| (source.trim().to_string(), alias.trim().to_string()), + ) + }) + .collect(); + Some((module, exports)) +} + +fn parse_python_lazy_export(line: &str) -> Option<(String, String, String)> { + let line = line.trim(); + let line = line.strip_prefix('"')?; + let (exported_symbol, line) = line.split_once("\": (\"")?; + let (module, source_symbol) = line.split_once("\", \"")?; + let source_symbol = source_symbol.strip_suffix("\"),")?; + Some(( + exported_symbol.to_string(), + module.to_string(), + source_symbol.to_string(), + )) +} + +fn merge_python_indexes( + existing: &str, + generated: &str, + suppressed_names: &HashSet, +) -> String { + let mut imports = BTreeSet::new(); + let mut exported_symbols = HashSet::new(); + for line in existing.lines().chain(generated.lines()) { + if line.starts_with("from .") { + let (line, comment) = line + .split_once(" #") + .map_or((line, None), |(line, comment)| (line, Some(comment))); + let Some((source, exports)) = line.split_once(" import ") else { + continue; + }; + let exports = exports + .split(',') + .map(str::trim) + .filter(|export| { + let source_symbol = export + .split_once(" as ") + .map_or(*export, |(name, _)| name.trim()); + let exported_symbol = export + .split_once(" as ") + .map_or(*export, |(_, alias)| alias.trim()); + !suppressed_names.contains(source_symbol) + && exported_symbols.insert(exported_symbol.to_string()) + }) + .collect::>(); + if !exports.is_empty() { + let mut import = format!("{source} import {}", exports.join(", ")); + if let Some(comment) = comment { + import.push_str(" #"); + import.push_str(comment); + } + imports.insert(import); + } + } + } + let mut merged = GENERATED_PYTHON_HEADER.to_string(); + for import in imports { + merged.push_str(&import); + merged.push('\n'); + } + merged +} + +const GENERATED_PYTHON_HEADER: &str = "# Generated by dynwinrt-codegen — do not edit\n"; + +fn python_generated_types( + classes: &[meta::ClassMeta], + interfaces: &[meta::InterfaceMeta], + enums: &[TypeMeta], +) -> Vec { + let mut types = Vec::new(); + types.extend(classes.iter().map(|class| PythonGeneratedType { + kind: "class".into(), + identity: python::PythonTypeIdentity { + namespace: class.namespace.clone(), + name: class.name.clone(), + }, + })); + types.extend(interfaces.iter().map(|interface| PythonGeneratedType { + kind: "interface".into(), + identity: python::PythonTypeIdentity { + namespace: interface.namespace.clone(), + name: interface.name.clone(), + }, + })); + types.extend(enums.iter().filter_map(|typ| { + let TypeMeta::Enum { + namespace, name, .. + } = typ + else { + return None; + }; + Some(PythonGeneratedType { + kind: "enum".into(), + identity: python::PythonTypeIdentity { + namespace: namespace.clone(), + name: name.clone(), + }, + }) + })); + types.extend( + python::package_struct_identities(classes, interfaces) + .into_iter() + .map(|(namespace, name)| PythonGeneratedType { + kind: "struct".into(), + identity: python::PythonTypeIdentity { namespace, name }, + }), + ); + types +} + +fn read_python_type_inventory(output_dir: &Path) -> Result, String> { + let path = output_dir.join(PYTHON_TYPE_INVENTORY); + if !path.is_file() { + return Ok(Vec::new()); + } + fs::read_to_string(&path) + .map_err(|e| format!("Failed to read {}: {}", path.display(), e))? + .lines() + .filter(|line| !line.is_empty()) + .map(|line| { + let mut parts = line.splitn(3, '|'); + let kind = parts.next().unwrap_or_default(); + let namespace = parts.next().unwrap_or_default(); + let name = parts.next().unwrap_or_default(); + if !matches!(kind, "class" | "interface" | "enum" | "struct") + || namespace.is_empty() + || name.is_empty() + { + return Err(format!("Invalid generated type inventory entry `{line}`")); + } + Ok(PythonGeneratedType { + kind: kind.into(), + identity: python::PythonTypeIdentity { + namespace: namespace.into(), + name: name.into(), + }, + }) + }) + .collect() +} + +fn write_python_type_inventory( + output_dir: &Path, + types: &[PythonGeneratedType], +) -> Result<(), String> { + let mut lines = types + .iter() + .map(|typ| { + format!( + "{}|{}|{}", + typ.kind, typ.identity.namespace, typ.identity.name + ) + }) + .collect::>(); + lines.sort(); + lines.dedup(); + write_file( + &output_dir.join(PYTHON_TYPE_INVENTORY), + &format!("{}\n", lines.join("\n")), + ) +} + +fn record_python_supplemental_types( + output_dir: &Path, + interfaces: &[meta::InterfaceMeta], +) -> Result<(), String> { + if interfaces.is_empty() { + return Ok(()); } - for typ in &group.enums { - let TypeMeta::Enum { name, .. } = typ else { - continue; - }; - if !seen.insert(name.clone()) { - continue; + let mut types = read_python_type_inventory(output_dir)?; + types.extend(python_generated_types(&[], interfaces, &[])); + let mut seen = HashSet::new(); + types.retain(|typ| seen.insert(typ.clone())); + write_python_type_inventory(output_dir, &types) +} + +#[cfg(test)] +fn validate_python_public_paths( + classes: &[meta::ClassMeta], + interfaces: &[meta::InterfaceMeta], + enums: &[TypeMeta], +) -> Result<(), String> { + let identities = python_type_identities(classes, interfaces, enums); + validate_python_public_identities(&identities) +} + +fn validate_python_public_identities( + identities: &[python::PythonTypeIdentity], +) -> Result<(), String> { + let mut namespace_owners = HashMap::::new(); + let mut namespace_paths = HashSet::new(); + for identity in identities { + let segments = python::python_namespace_segments(&identity.namespace); + let normalized = segments.join("/"); + if let Some(existing) = + namespace_owners.insert(normalized.clone(), identity.namespace.clone()) + { + if existing != identity.namespace { + return Err(format!( + "Python namespace collision: `{existing}` and `{}` both normalize to `{normalized}`", + identity.namespace + )); + } } - let runtime = python::generate_index(&[], &[], std::slice::from_ref(typ)); - write_python_facade( - &package_dir, - &segments, - name, - &runtime, - "py", - &mut runtime_exports, - )?; - if pyi { - let stub = python_stub::generate_index_stub(&[], &[], std::slice::from_ref(typ)); - write_python_facade( - &package_dir, - &segments, - name, - &stub, - "pyi", - &mut stub_exports, - )?; + for depth in 1..=segments.len() { + namespace_paths.insert(segments[..depth].join("/")); } } - for typ in &group.structs { - let TypeMeta::Struct { name, .. } = typ else { - continue; - }; - if !seen.insert(name.clone()) { - continue; - } - let runtime = python::generate_struct_index(std::slice::from_ref(typ)); - if runtime.lines().any(|line| line.starts_with("from .")) { - write_python_facade( - &package_dir, - &segments, - name, - &runtime, - "py", - &mut runtime_exports, - )?; + + let mut module_owners = HashMap::::new(); + for identity in identities { + let mut segments = python::python_namespace_segments(&identity.namespace); + segments.push(python::python_public_module_name(&identity.name)); + let module_path = segments.join("/"); + if namespace_paths.contains(&module_path) { + return Err(format!( + "Python package/module collision: `{}.{}` normalizes to package path `{module_path}`", + identity.namespace, identity.name + )); } - if pyi { - let stub = python_stub::generate_struct_index_stub(std::slice::from_ref(typ)); - if stub.lines().any(|line| line.starts_with("from .")) { - write_python_facade( - &package_dir, - &segments, - name, - &stub, - "pyi", - &mut stub_exports, - )?; + if let Some(existing) = module_owners.insert(module_path.clone(), identity.clone()) { + if existing != *identity { + return Err(format!( + "Python module collision: `{}.{}` and `{}.{}` both normalize to `{module_path}.py`", + existing.namespace, existing.name, identity.namespace, identity.name + )); } } } - - let runtime_index = format!("{}{}", GENERATED_PYTHON_HEADER, runtime_exports.join("\n")); - let suppressed_root_names = HashSet::new(); - write_python_lazy_root_index( - &package_dir.join("__init__.py"), - &runtime_index, - append, - &suppressed_root_names, - )?; - if pyi { - let stub_index = format!("{}{}", GENERATED_PYTHON_HEADER, stub_exports.join("\n")); - write_python_index( - &package_dir.join("__init__.pyi"), - &stub_index, - append, - &suppressed_root_names, - )?; - } Ok(()) } - -fn write_python_facade( - package_dir: &Path, - namespace_segments: &[String], - type_name: &str, - implementation_index: &str, - extension: &str, - package_exports: &mut Vec, -) -> Result<(), String> { - let import_line = implementation_index - .lines() - .find(|line| line.starts_with("from .")) - .ok_or_else(|| format!("Generated index for `{type_name}` has no import"))?; - let (source, exports) = import_line - .strip_prefix("from .") - .and_then(|line| line.split_once(" import ")) - .ok_or_else(|| format!("Generated index import for `{type_name}` is invalid"))?; - let exports = exports.split('#').next().unwrap_or(exports).trim(); - let exported_type = exports.split(',').any(|export| { - export - .trim() - .split_once(" as ") - .map_or_else(|| export.trim(), |(_, alias)| alias.trim()) - == type_name - }); - let exports = if extension == "pyi" { - exports - .split(',') - .map(|export| { - let export = export.trim(); - if export.contains(" as ") { - export.to_string() - } else { - format!("{export} as {export}") - } - }) - .collect::>() - .join(", ") + +fn output_contains_current_directory(output_dir: &Path) -> Result { + if output_dir.as_os_str().is_empty() { + return Err("Generated output directory cannot be empty.".into()); + } + let current = std::env::current_dir() + .and_then(fs::canonicalize) + .map_err(|error| format!("Failed to resolve current directory: {error}"))?; + let absolute = if output_dir.is_absolute() { + output_dir.to_path_buf() } else { - exports.to_string() + current.join(output_dir) }; - let relative_root = ".".repeat(namespace_segments.len() + 1); - let mut facade = - format!("{GENERATED_PYTHON_HEADER}from {relative_root}{source} import {exports}\n"); - if extension == "py" && exported_type { - facade.push_str(&format!("\n{type_name}.__module__ = __name__\n")); + let output = if absolute.exists() { + fs::canonicalize(&absolute) + .map_err(|error| format!("Failed to resolve {}: {error}", absolute.display()))? + } else { + let mut ancestor = absolute.as_path(); + let mut missing = Vec::new(); + while !ancestor.exists() { + let leaf = ancestor.file_name().ok_or_else(|| { + format!( + "Invalid generated output directory '{}'", + output_dir.display() + ) + })?; + missing.push(leaf.to_os_string()); + ancestor = ancestor.parent().ok_or_else(|| { + format!( + "Invalid generated output directory '{}'", + output_dir.display() + ) + })?; + } + let mut resolved = fs::canonicalize(ancestor) + .map_err(|error| format!("Failed to resolve {}: {error}", ancestor.display()))?; + for component in missing.into_iter().rev() { + resolved.push(component); + } + resolved + }; + Ok(current.starts_with(output)) +} + +struct OutputTransaction { + final_dir: PathBuf, + stage_dir: PathBuf, + backup_dir: PathBuf, + nonce: String, + had_existing_output: bool, + lock_file: Option, + committed: bool, +} + +const OUTPUT_TRANSACTION_OWNER: &str = ".dynwinrt-transaction-owner"; + +fn transaction_nonce(final_dir: &Path) -> String { + static NEXT_NONCE: AtomicU64 = AtomicU64::new(0); + let timestamp = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_nanos(); + let sequence = NEXT_NONCE.fetch_add(1, Ordering::Relaxed); + let mut hasher = std::collections::hash_map::RandomState::new().build_hasher(); + final_dir.hash(&mut hasher); + timestamp.hash(&mut hasher); + std::process::id().hash(&mut hasher); + sequence.hash(&mut hasher); + format!("{timestamp:032x}{:016x}", hasher.finish()) +} + +fn transaction_owner_path(directory: &Path) -> PathBuf { + directory.join(OUTPUT_TRANSACTION_OWNER) +} + +fn write_transaction_owner(directory: &Path, nonce: &str) -> Result<(), String> { + let marker = transaction_owner_path(directory); + let mut file = fs::OpenOptions::new() + .create_new(true) + .write(true) + .open(&marker) + .map_err(|error| format!("Failed to create {}: {error}", marker.display()))?; + use std::io::Write; + file.write_all(nonce.as_bytes()) + .map_err(|error| format!("Failed to write {}: {error}", marker.display())) +} + +fn validate_transaction_owner(directory: &Path, nonce: &str) -> Result<(), String> { + let metadata = fs::symlink_metadata(directory) + .map_err(|error| format!("Failed to inspect {}: {error}", directory.display()))?; + if is_link_or_reparse_point(&metadata) || !metadata.is_dir() { + return Err(format!( + "Invalid generated output transaction directory '{}'", + directory.display() + )); } - let public_module = python::python_public_module_name(type_name); - write_file( - &package_dir.join(format!("{public_module}.{extension}")), - &facade, - )?; - if exported_type { - let package_export = if extension == "pyi" { - format!("from .{public_module} import {type_name} as {type_name}") - } else { - format!("from .{public_module} import {type_name}") - }; - package_exports.push(package_export); + let marker = transaction_owner_path(directory); + let metadata = fs::symlink_metadata(&marker) + .map_err(|error| format!("Missing ownership marker '{}': {error}", marker.display()))?; + if is_link_or_reparse_point(&metadata) || !metadata.is_file() { + return Err(format!( + "Invalid transaction ownership marker '{}'", + marker.display() + )); + } + let actual = fs::read_to_string(&marker) + .map_err(|error| format!("Failed to read {}: {error}", marker.display()))?; + if actual != nonce { + return Err(format!( + "Transaction ownership marker '{}' does not match the active transaction", + marker.display() + )); } Ok(()) } -fn write_python_index( - path: &Path, - generated: &str, - append: bool, - suppressed_names: &HashSet, -) -> Result<(), String> { - let content = if append && path.exists() { - let existing = fs::read_to_string(path) - .map_err(|e| format!("Failed to read {}: {}", path.display(), e))?; - merge_python_indexes(&existing, generated, suppressed_names) - } else { - merge_python_indexes(GENERATED_PYTHON_HEADER, generated, suppressed_names) - }; - write_file(path, &content) +fn remove_transaction_owner(directory: &Path, nonce: &str) -> Result<(), String> { + validate_transaction_owner(directory, nonce)?; + let marker = transaction_owner_path(directory); + fs::remove_file(&marker) + .map_err(|error| format!("Failed to remove {}: {error}", marker.display())) } -fn write_python_lazy_root_index( - path: &Path, - generated: &str, - append: bool, - suppressed_names: &HashSet, -) -> Result<(), String> { - let existing = if append && path.exists() { - fs::read_to_string(path).map_err(|e| format!("Failed to read {}: {}", path.display(), e))? - } else { - GENERATED_PYTHON_HEADER.to_string() - }; - let content = merge_python_lazy_root_indexes(&existing, generated, suppressed_names); - write_file(path, &content) +fn remove_owned_transaction_dir(directory: &Path, nonce: &str) -> Result<(), String> { + if !directory.exists() { + return Ok(()); + } + validate_transaction_owner(directory, nonce)?; + fs::remove_dir_all(directory) + .map_err(|error| format!("Failed to remove {}: {error}", directory.display())) } -fn merge_python_lazy_root_indexes( - existing: &str, - generated: &str, - suppressed_names: &HashSet, -) -> String { - let mut exports = BTreeMap::::new(); - collect_python_root_exports(existing, suppressed_names, &mut exports); - collect_python_root_exports(generated, suppressed_names, &mut exports); +fn ensure_no_orphaned_transaction_artifacts(parent: &Path, leaf: &str) -> Result<(), String> { + let stage_prefix = format!(".{leaf}.dynwinrt-stage-").to_ascii_lowercase(); + let backup_prefix = format!(".{leaf}.dynwinrt-backup-").to_ascii_lowercase(); + for entry in fs::read_dir(parent) + .map_err(|error| format!("Failed to inspect {}: {error}", parent.display()))? + { + let entry = + entry.map_err(|error| format!("Failed to inspect transaction entry: {error}"))?; + let name = entry.file_name().to_string_lossy().to_ascii_lowercase(); + if name.starts_with(&stage_prefix) || name.starts_with(&backup_prefix) { + return Err(format!( + "Incomplete generated output transaction artifact '{}' must be recovered or removed manually", + entry.path().display() + )); + } + } + Ok(()) +} - let mut out = String::from(GENERATED_PYTHON_HEADER); - out.push_str("from importlib import import_module as _import_module\n\n"); - out.push_str("__all__ = (\n"); - for name in exports.keys() { - out.push_str(&format!(" \"{name}\",\n")); +impl OutputTransaction { + fn begin(requested_final_dir: &Path) -> Result { + let absolute = if requested_final_dir.is_absolute() { + requested_final_dir.to_path_buf() + } else { + std::env::current_dir() + .map_err(|e| format!("Failed to resolve current directory: {e}"))? + .join(requested_final_dir) + }; + let final_dir = if absolute.exists() { + let metadata = fs::symlink_metadata(&absolute) + .map_err(|e| format!("Failed to inspect {}: {}", absolute.display(), e))?; + if is_link_or_reparse_point(&metadata) { + return Err(format!( + "Generated output path '{}' cannot be a linked directory", + requested_final_dir.display() + )); + } + fs::canonicalize(&absolute) + .map_err(|e| format!("Failed to resolve {}: {}", absolute.display(), e))? + } else { + let leaf = absolute.file_name().ok_or_else(|| { + format!( + "Invalid generated output directory '{}'", + requested_final_dir.display() + ) + })?; + let parent = absolute.parent().unwrap_or_else(|| Path::new(".")); + fs::create_dir_all(parent) + .map_err(|e| format!("Failed to create {}: {}", parent.display(), e))?; + fs::canonicalize(parent) + .map_err(|e| format!("Failed to resolve {}: {}", parent.display(), e))? + .join(leaf) + }; + let parent = final_dir.parent().unwrap_or_else(|| Path::new(".")); + let leaf = final_dir + .file_name() + .and_then(|name| name.to_str()) + .ok_or_else(|| { + format!( + "Invalid generated output directory '{}'", + requested_final_dir.display() + ) + })?; + fs::create_dir_all(parent) + .map_err(|e| format!("Failed to create {}: {}", parent.display(), e))?; + + let lock_path = parent.join(format!(".{}.dynwinrt-lock", leaf)); + if lock_path.exists() { + let metadata = fs::symlink_metadata(&lock_path) + .map_err(|error| format!("Failed to inspect {}: {error}", lock_path.display()))?; + if is_link_or_reparse_point(&metadata) || !metadata.is_file() { + return Err(format!( + "Invalid generated output lock '{}'", + lock_path.display() + )); + } + } + let lock_file = fs::OpenOptions::new() + .create(true) + .read(true) + .write(true) + .open(&lock_path) + .map_err(|error| { + format!( + "Failed to open generated output lock '{}': {error}", + lock_path.display() + ) + })?; + lock_file.try_lock().map_err(|error| { + format!( + "Another generation is already using output directory '{}': {error}", + final_dir.display() + ) + })?; + + ensure_no_orphaned_transaction_artifacts(parent, leaf)?; + let nonce = transaction_nonce(&final_dir); + let stage_dir = parent.join(format!(".{leaf}.dynwinrt-stage-{nonce}")); + let backup_dir = parent.join(format!(".{leaf}.dynwinrt-backup-{nonce}")); + if stage_dir.exists() || backup_dir.exists() { + return Err("Generated output transaction nonce collision".into()); + } + fs::create_dir(&stage_dir) + .map_err(|error| format!("Failed to create {}: {error}", stage_dir.display()))?; + if let Err(error) = write_transaction_owner(&stage_dir, &nonce) { + let _ = fs::remove_dir(&stage_dir); + return Err(error); + } + let had_existing_output = final_dir.exists(); + if had_existing_output { + if !final_dir.is_dir() { + let _ = remove_owned_transaction_dir(&stage_dir, &nonce); + return Err(format!( + "Generated output path '{}' is not a directory", + final_dir.display() + )); + } + if transaction_owner_path(&final_dir).exists() { + let _ = remove_owned_transaction_dir(&stage_dir, &nonce); + return Err(format!( + "Generated output '{}' contains a reserved transaction ownership marker", + final_dir.display() + )); + } + if let Err(error) = copy_directory(&final_dir, &stage_dir) { + let _ = remove_owned_transaction_dir(&stage_dir, &nonce); + return Err(error); + } + } + + Ok(Self { + final_dir, + stage_dir, + backup_dir, + nonce, + had_existing_output, + lock_file: Some(lock_file), + committed: false, + }) } - out.push_str(")\n\n"); - out.push_str("_EXPORTS = {\n"); - for (name, (module, symbol)) in &exports { - out.push_str(&format!(" \"{name}\": (\"{module}\", \"{symbol}\"),\n")); + + fn stage_dir(&self) -> &Path { + &self.stage_dir + } + + fn commit(mut self) -> Result<(), String> { + validate_transaction_owner(&self.stage_dir, &self.nonce)?; + let had_existing_output = self.had_existing_output; + let cwd_relative = std::env::current_dir() + .ok() + .and_then(|cwd| fs::canonicalize(cwd).ok()) + .and_then(|cwd| { + cwd.strip_prefix(&self.final_dir) + .ok() + .map(Path::to_path_buf) + }); + if cwd_relative.is_some() { + let parent = self.final_dir.parent().unwrap_or_else(|| Path::new(".")); + std::env::set_current_dir(parent).map_err(|e| { + format!( + "Failed to leave generated output directory '{}' before replacement: {}", + self.final_dir.display(), + e + ) + })?; + } + let cwd_output_dir = self.final_dir.clone(); + let restore_cwd = |relative: &Option| -> Result<(), String> { + if let Some(relative) = relative { + let destination = cwd_output_dir.join(relative); + std::env::set_current_dir(&destination).map_err(|e| { + format!( + "Failed to restore current directory '{}': {}", + destination.display(), + e + ) + })?; + } + Ok(()) + }; + if had_existing_output { + write_transaction_owner(&self.final_dir, &self.nonce)?; + if let Err(error) = fs::rename(&self.final_dir, &self.backup_dir) { + let _ = remove_transaction_owner(&self.final_dir, &self.nonce); + let restore_error = restore_cwd(&cwd_relative).err(); + return Err(format!( + "Failed to stage existing output '{}' for replacement: {}", + self.final_dir.display(), + error + ) + &restore_error + .map(|error| format!(". {error}")) + .unwrap_or_default()); + } + } + + if let Err(error) = fs::rename(&self.stage_dir, &self.final_dir) { + if had_existing_output { + if let Err(rollback_error) = fs::rename(&self.backup_dir, &self.final_dir) { + return Err(format!( + "Failed to replace generated output directory '{}': {}. Rollback also failed: \ + {}. The original output remains at '{}'", + self.final_dir.display(), + error, + rollback_error, + self.backup_dir.display() + )); + } + let _ = remove_transaction_owner(&self.final_dir, &self.nonce); + } + let restore_error = restore_cwd(&cwd_relative).err(); + return Err(format!( + "Failed to replace generated output directory '{}': {}", + self.final_dir.display(), + error + ) + &restore_error + .map(|error| format!(". {error}")) + .unwrap_or_default()); + } + + restore_cwd(&cwd_relative)?; + if had_existing_output { + validate_transaction_owner(&self.final_dir, &self.nonce)?; + remove_owned_transaction_dir(&self.backup_dir, &self.nonce)?; + } + remove_transaction_owner(&self.final_dir, &self.nonce)?; + self.committed = true; + Ok(()) } - out.push_str( - "}\n\n\ - \n\ - def __getattr__(name):\n\ - \x20 try:\n\ - \x20 module_name, symbol_name = _EXPORTS[name]\n\ - \x20 except KeyError:\n\ - \x20 raise AttributeError(\n\ - \x20 f\"module {__name__!r} has no attribute {name!r}\"\n\ - \x20 ) from None\n\ - \x20 value = getattr(_import_module(module_name, __name__), symbol_name)\n\ - \x20 globals()[name] = value\n\ - \x20 return value\n\ - \n\ - \n\ - def __dir__():\n\ - \x20 return sorted(set(globals()) | set(__all__))\n", - ); - out } -fn collect_python_root_exports( - content: &str, - suppressed_names: &HashSet, - exports: &mut BTreeMap, -) { - for line in content.lines() { - if let Some((module, symbols)) = parse_python_import_line(line) { - for (source_symbol, exported_symbol) in symbols { - if suppressed_names.contains(&source_symbol) - || suppressed_names.contains(&exported_symbol) +impl Drop for OutputTransaction { + fn drop(&mut self) { + if !self.committed { + if self.backup_dir.exists() { + if self.final_dir.exists() { + if validate_transaction_owner(&self.final_dir, &self.nonce).is_ok() + && validate_transaction_owner(&self.backup_dir, &self.nonce).is_ok() + { + let _ = remove_owned_transaction_dir(&self.backup_dir, &self.nonce); + let _ = remove_transaction_owner(&self.final_dir, &self.nonce); + } + } else if validate_transaction_owner(&self.backup_dir, &self.nonce).is_ok() + && fs::rename(&self.backup_dir, &self.final_dir).is_ok() { - continue; + let _ = remove_transaction_owner(&self.final_dir, &self.nonce); } - exports - .entry(exported_symbol) - .or_insert_with(|| (module.clone(), source_symbol)); } - } else if let Some((exported_symbol, module, source_symbol)) = - parse_python_lazy_export(line) - { - if suppressed_names.contains(&source_symbol) - || suppressed_names.contains(&exported_symbol) - { - continue; + if self.stage_dir.exists() { + let _ = remove_owned_transaction_dir(&self.stage_dir, &self.nonce); } - exports - .entry(exported_symbol) - .or_insert((module, source_symbol)); + } + drop(self.lock_file.take()); + } +} + +fn copy_directory(source: &Path, destination: &Path) -> Result<(), String> { + fs::create_dir_all(destination) + .map_err(|e| format!("Failed to create {}: {}", destination.display(), e))?; + for entry in + fs::read_dir(source).map_err(|e| format!("Failed to read {}: {}", source.display(), e))? + { + let entry = + entry.map_err(|e| format!("Failed to read entry in {}: {}", source.display(), e))?; + let source_path = entry.path(); + let destination_path = destination.join(entry.file_name()); + let metadata = fs::symlink_metadata(&source_path) + .map_err(|e| format!("Failed to inspect {}: {}", source_path.display(), e))?; + if is_link_or_reparse_point(&metadata) { + return Err(format!( + "Unsupported linked filesystem entry in generated output: {}", + source_path.display() + )); + } + if metadata.is_dir() { + copy_directory(&source_path, &destination_path)?; + } else if metadata.is_file() { + fs::copy(&source_path, &destination_path).map_err(|e| { + format!( + "Failed to copy {} to {}: {}", + source_path.display(), + destination_path.display(), + e + ) + })?; + } else { + return Err(format!( + "Unsupported filesystem entry in generated output: {}", + source_path.display() + )); } } + Ok(()) } -fn parse_python_import_line(line: &str) -> Option<(String, Vec<(String, String)>)> { - let line = line.split_once(" #").map_or(line, |(line, _)| line); - let (source, exports) = line.split_once(" import ")?; - let module = source.strip_prefix("from ")?.to_string(); - if !module.starts_with('.') { - return None; +fn write_python_package_manifest(output_dir: &Path, final_output_dir: &Path) -> Result<(), String> { + let manifest_path = output_dir.join("pyproject.toml"); + if manifest_path.exists() + && !python_inventory_contains(output_dir, Path::new("pyproject.toml"))? + { + return Err(format!( + "Refusing to overwrite existing non-generated manifest '{}'", + final_output_dir.join("pyproject.toml").display() + )); } - let exports = exports - .split(',') - .map(str::trim) - .filter(|export| !export.is_empty()) - .map(|export| { - export.split_once(" as ").map_or_else( - || (export.to_string(), export.to_string()), - |(source, alias)| (source.trim().to_string(), alias.trim().to_string()), + let leaf = final_output_dir + .file_name() + .and_then(|name| name.to_str()) + .ok_or_else(|| { + format!( + "Cannot derive Python package name from '{}'", + final_output_dir.display() ) - }) - .collect(); - Some((module, exports)) + })?; + let import_name = normalize_python_package_name(leaf); + let distribution_name = import_name.replace('_', "-"); + let version = env!("CARGO_PKG_VERSION"); + let namespace_packages = collect_python_namespace_packages(output_dir)?; + let manifest = package::render_python_pyproject(&package::PythonPackageManifestInput { + distribution_name: &distribution_name, + import_name: &import_name, + package_version: version, + runtime_version: version, + namespace_packages: &namespace_packages, + }); + write_file(&manifest_path, &manifest) } -fn parse_python_lazy_export(line: &str) -> Option<(String, String, String)> { - let line = line.trim(); - let line = line.strip_prefix('"')?; - let (exported_symbol, line) = line.split_once("\": (\"")?; - let (module, source_symbol) = line.split_once("\", \"")?; - let source_symbol = source_symbol.strip_suffix("\"),")?; - Some(( - exported_symbol.to_string(), - module.to_string(), - source_symbol.to_string(), - )) +const PYTHON_GENERATED_INVENTORY: &str = ".dynwinrt-generated-files"; +const PYTHON_TYPE_INVENTORY: &str = ".dynwinrt-generated-types"; + +fn python_inventory_contains(output_dir: &Path, relative_path: &Path) -> Result { + let inventory_path = output_dir.join(PYTHON_GENERATED_INVENTORY); + if !inventory_path.is_file() { + return Ok(false); + } + Ok(fs::read_to_string(&inventory_path) + .map_err(|e| format!("Failed to read {}: {}", inventory_path.display(), e))? + .lines() + .map(Path::new) + .any(|path| path == relative_path)) } -fn merge_python_indexes( - existing: &str, - generated: &str, - suppressed_names: &HashSet, -) -> String { - let mut imports = BTreeSet::new(); - let mut exported_symbols = HashSet::new(); - for line in existing.lines().chain(generated.lines()) { - if line.starts_with("from .") { - let (line, comment) = line - .split_once(" #") - .map_or((line, None), |(line, comment)| (line, Some(comment))); - let Some((source, exports)) = line.split_once(" import ") else { - continue; - }; - let exports = exports - .split(',') - .map(str::trim) - .filter(|export| { - let source_symbol = export - .split_once(" as ") - .map_or(*export, |(name, _)| name.trim()); - let exported_symbol = export - .split_once(" as ") - .map_or(*export, |(_, alias)| alias.trim()); - !suppressed_names.contains(source_symbol) - && exported_symbols.insert(exported_symbol.to_string()) - }) - .collect::>(); - if !exports.is_empty() { - let mut import = format!("{source} import {}", exports.join(", ")); - if let Some(comment) = comment { - import.push_str(" #"); - import.push_str(comment); - } - imports.insert(import); +fn remove_all_generated_python_stubs(output_dir: &Path) -> Result<(), String> { + let inventory_path = output_dir.join(PYTHON_GENERATED_INVENTORY); + if inventory_path.is_file() { + for relative in fs::read_to_string(&inventory_path) + .map_err(|e| format!("Failed to read {}: {}", inventory_path.display(), e))? + .lines() + .map(PathBuf::from) + { + if !is_safe_relative_path(&relative) { + return Err(format!( + "Invalid path `{}` in {}", + relative.display(), + inventory_path.display() + )); + } + let is_stub = relative + .extension() + .is_some_and(|extension| extension == "pyi") + || relative.file_name().is_some_and(|name| name == "py.typed"); + let path = output_dir.join(relative); + if is_stub && path.is_file() { + fs::remove_file(&path) + .map_err(|e| format!("Failed to remove {}: {}", path.display(), e))?; } } + return Ok(()); } - let mut merged = GENERATED_PYTHON_HEADER.to_string(); - for import in imports { - merged.push_str(&import); - merged.push('\n'); + + fn visit(current: &Path) -> Result<(), String> { + for entry in fs::read_dir(current) + .map_err(|e| format!("Failed to inspect {}: {}", current.display(), e))? + { + let entry = entry + .map_err(|e| format!("Failed to inspect entry in {}: {}", current.display(), e))?; + let path = entry.path(); + let file_type = entry + .file_type() + .map_err(|e| format!("Failed to inspect {}: {}", path.display(), e))?; + if file_type.is_dir() { + visit(&path)?; + } else if file_type.is_file() + && path.extension().is_some_and(|extension| extension == "pyi") + { + let generated = fs::read_to_string(&path) + .map_err(|e| format!("Failed to inspect {}: {}", path.display(), e))? + .starts_with("# Generated by dynwinrt-codegen"); + if generated { + fs::remove_file(&path) + .map_err(|e| format!("Failed to remove {}: {}", path.display(), e))?; + } + } + } + Ok(()) } - merged + visit(output_dir) } -const GENERATED_PYTHON_HEADER: &str = "# Generated by dynwinrt-codegen — do not edit\n"; - -fn python_generated_types( - classes: &[meta::ClassMeta], - interfaces: &[meta::InterfaceMeta], - enums: &[TypeMeta], -) -> Vec { - let mut types = Vec::new(); - types.extend(classes.iter().map(|class| PythonGeneratedType { - kind: "class".into(), - identity: python::PythonTypeIdentity { - namespace: class.namespace.clone(), - name: class.name.clone(), - }, - })); - types.extend(interfaces.iter().map(|interface| PythonGeneratedType { - kind: "interface".into(), - identity: python::PythonTypeIdentity { - namespace: interface.namespace.clone(), - name: interface.name.clone(), - }, - })); - types.extend(enums.iter().filter_map(|typ| { - let TypeMeta::Enum { - namespace, name, .. - } = typ - else { - return None; - }; - Some(PythonGeneratedType { - kind: "enum".into(), - identity: python::PythonTypeIdentity { - namespace: namespace.clone(), - name: name.clone(), - }, - }) - })); - types.extend( - python::package_struct_identities(classes, interfaces) - .into_iter() - .map(|(namespace, name)| PythonGeneratedType { - kind: "struct".into(), - identity: python::PythonTypeIdentity { namespace, name }, - }), - ); - types -} +fn clean_python_generated_output(output_dir: &Path) -> Result<(), String> { + let inventory_path = output_dir.join(PYTHON_GENERATED_INVENTORY); + let files = if inventory_path.is_file() { + fs::read_to_string(&inventory_path) + .map_err(|e| format!("Failed to read {}: {}", inventory_path.display(), e))? + .lines() + .map(PathBuf::from) + .collect::>() + } else { + collect_generated_python_files(output_dir, false, false)? + }; -fn read_python_type_inventory(output_dir: &Path) -> Result, String> { - let path = output_dir.join(PYTHON_TYPE_INVENTORY); - if !path.is_file() { - return Ok(Vec::new()); + let mut parent_dirs = HashSet::new(); + for relative in files { + if !is_safe_relative_path(&relative) { + return Err(format!( + "Invalid path `{}` in {}", + relative.display(), + inventory_path.display() + )); + } + let path = output_dir.join(&relative); + if path.is_file() { + fs::remove_file(&path) + .map_err(|e| format!("Failed to remove stale {}: {}", path.display(), e))?; + } + if let Some(parent) = relative.parent() { + if !parent.as_os_str().is_empty() { + parent_dirs.insert(parent.to_path_buf()); + } + } } - fs::read_to_string(&path) - .map_err(|e| format!("Failed to read {}: {}", path.display(), e))? - .lines() - .filter(|line| !line.is_empty()) - .map(|line| { - let mut parts = line.splitn(3, '|'); - let kind = parts.next().unwrap_or_default(); - let namespace = parts.next().unwrap_or_default(); - let name = parts.next().unwrap_or_default(); - if !matches!(kind, "class" | "interface" | "enum" | "struct") - || namespace.is_empty() - || name.is_empty() - { - return Err(format!("Invalid generated type inventory entry `{line}`")); + if inventory_path.is_file() { + fs::remove_file(&inventory_path) + .map_err(|e| format!("Failed to remove {}: {}", inventory_path.display(), e))?; + } + let type_inventory = output_dir.join(PYTHON_TYPE_INVENTORY); + if type_inventory.is_file() { + fs::remove_file(&type_inventory) + .map_err(|e| format!("Failed to remove {}: {}", type_inventory.display(), e))?; + } + + let mut parent_dirs = parent_dirs.into_iter().collect::>(); + parent_dirs.sort_by_key(|path| std::cmp::Reverse(path.components().count())); + for relative in parent_dirs { + let path = output_dir.join(relative); + if path.is_dir() { + match fs::remove_dir(&path) { + Ok(()) => {} + Err(error) if error.kind() == std::io::ErrorKind::DirectoryNotEmpty => {} + Err(error) => { + return Err(format!( + "Failed to remove stale package directory {}: {}", + path.display(), + error + )); + } } - Ok(PythonGeneratedType { - kind: kind.into(), - identity: python::PythonTypeIdentity { - namespace: namespace.into(), - name: name.into(), - }, - }) - }) - .collect() + } + } + Ok(()) } -fn write_python_type_inventory( - output_dir: &Path, - types: &[PythonGeneratedType], -) -> Result<(), String> { - let mut lines = types +fn write_python_generated_inventory(output_dir: &Path, pyi: bool) -> Result<(), String> { + let files = collect_generated_python_files(output_dir, true, pyi)?; + let content = files .iter() - .map(|typ| { - format!( - "{}|{}|{}", - typ.kind, typ.identity.namespace, typ.identity.name - ) - }) - .collect::>(); - lines.sort(); - lines.dedup(); + .map(|path| path.to_string_lossy()) + .collect::>() + .join("\n"); write_file( - &output_dir.join(PYTHON_TYPE_INVENTORY), - &format!("{}\n", lines.join("\n")), + &output_dir.join(PYTHON_GENERATED_INVENTORY), + &format!("{content}\n"), ) } -fn record_python_supplemental_types( +fn collect_generated_python_files( output_dir: &Path, - interfaces: &[meta::InterfaceMeta], -) -> Result<(), String> { - if interfaces.is_empty() { - return Ok(()); + include_root_manifest: bool, + include_root_marker: bool, +) -> Result, String> { + fn visit( + root: &Path, + current: &Path, + include_root_manifest: bool, + include_root_marker: bool, + files: &mut Vec, + ) -> Result<(), String> { + for entry in fs::read_dir(current) + .map_err(|e| format!("Failed to inspect {}: {}", current.display(), e))? + { + let entry = entry + .map_err(|e| format!("Failed to inspect entry in {}: {}", current.display(), e))?; + let path = entry.path(); + let file_type = entry + .file_type() + .map_err(|e| format!("Failed to inspect {}: {}", path.display(), e))?; + if file_type.is_dir() { + visit( + root, + &path, + include_root_manifest, + include_root_marker, + files, + )?; + continue; + } + if !file_type.is_file() || entry.file_name() == PYTHON_GENERATED_INVENTORY { + continue; + } + + let generated = match entry.file_name().to_str() { + Some("py.typed") => include_root_marker && current == root, + Some("pyproject.toml") => include_root_manifest && current == root, + Some(name) if name.ends_with(".py") || name.ends_with(".pyi") => { + fs::read_to_string(&path) + .map_err(|e| format!("Failed to inspect {}: {}", path.display(), e))? + .starts_with("# Generated by dynwinrt-codegen") + } + _ => false, + }; + if generated { + files.push(path.strip_prefix(root).unwrap().to_path_buf()); + } + } + Ok(()) } - let mut types = read_python_type_inventory(output_dir)?; - types.extend(python_generated_types(&[], interfaces, &[])); - let mut seen = HashSet::new(); - types.retain(|typ| seen.insert(typ.clone())); - write_python_type_inventory(output_dir, &types) + + let mut files = Vec::new(); + visit( + output_dir, + output_dir, + include_root_manifest, + include_root_marker, + &mut files, + )?; + files.sort(); + Ok(files) } -#[cfg(test)] -fn validate_python_public_paths( - classes: &[meta::ClassMeta], - interfaces: &[meta::InterfaceMeta], - enums: &[TypeMeta], -) -> Result<(), String> { - let identities = python_type_identities(classes, interfaces, enums); - validate_python_public_identities(&identities) +fn is_safe_relative_path(path: &Path) -> bool { + !path.as_os_str().is_empty() + && path + .components() + .all(|component| matches!(component, std::path::Component::Normal(_))) } -fn validate_python_public_identities( - identities: &[python::PythonTypeIdentity], -) -> Result<(), String> { - let mut namespace_owners = HashMap::::new(); - let mut namespace_paths = HashSet::new(); - for identity in identities { - let segments = python::python_namespace_segments(&identity.namespace); - let normalized = segments.join("/"); - if let Some(existing) = - namespace_owners.insert(normalized.clone(), identity.namespace.clone()) +fn collect_python_namespace_packages(output_dir: &Path) -> Result, String> { + fn visit(root: &Path, current: &Path, packages: &mut Vec) -> Result<(), String> { + for entry in fs::read_dir(current) + .map_err(|e| format!("Failed to inspect {}: {}", current.display(), e))? { - if existing != identity.namespace { - return Err(format!( - "Python namespace collision: `{existing}` and `{}` both normalize to `{normalized}`", - identity.namespace - )); + let entry = entry + .map_err(|e| format!("Failed to inspect entry in {}: {}", current.display(), e))?; + if !entry + .file_type() + .map_err(|e| format!("Failed to inspect {}: {}", entry.path().display(), e))? + .is_dir() + { + continue; } - } - for depth in 1..=segments.len() { - namespace_paths.insert(segments[..depth].join("/")); - } - } - - let mut module_owners = HashMap::::new(); - for identity in identities { - let mut segments = python::python_namespace_segments(&identity.namespace); - segments.push(python::python_public_module_name(&identity.name)); - let module_path = segments.join("/"); - if namespace_paths.contains(&module_path) { - return Err(format!( - "Python package/module collision: `{}.{}` normalizes to package path `{module_path}`", - identity.namespace, identity.name - )); - } - if let Some(existing) = module_owners.insert(module_path.clone(), identity.clone()) { - if existing != *identity { - return Err(format!( - "Python module collision: `{}.{}` and `{}.{}` both normalize to `{module_path}.py`", - existing.namespace, existing.name, identity.namespace, identity.name - )); + let path = entry.path(); + if path.join("__init__.py").is_file() { + let relative = path.strip_prefix(root).map_err(|e| { + format!("Failed to normalize package path {}: {}", path.display(), e) + })?; + packages.push( + relative + .components() + .map(|component| component.as_os_str().to_string_lossy()) + .collect::>() + .join("."), + ); } + visit(root, &path, packages)?; } + Ok(()) } - Ok(()) -} -struct PythonOutputTransaction { - final_dir: PathBuf, - stage_dir: PathBuf, - backup_dir: PathBuf, - committed: bool, + let mut packages = Vec::new(); + visit(output_dir, output_dir, &mut packages)?; + packages.sort(); + Ok(packages) } -impl PythonOutputTransaction { - fn begin(final_dir: &Path) -> Result { - let parent = final_dir.parent().unwrap_or_else(|| Path::new(".")); - let leaf = final_dir - .file_name() - .and_then(|name| name.to_str()) - .ok_or_else(|| format!("Invalid Python output directory '{}'", final_dir.display()))?; - fs::create_dir_all(parent) - .map_err(|e| format!("Failed to create {}: {}", parent.display(), e))?; - - let suffix = std::process::id(); - let stage_dir = parent.join(format!(".{}.dynwinrt-stage-{}", leaf, suffix)); - let backup_dir = parent.join(format!(".{}.dynwinrt-backup-{}", leaf, suffix)); - remove_transaction_dir(&stage_dir)?; - remove_transaction_dir(&backup_dir)?; - - if final_dir.exists() { - if !final_dir.is_dir() { - return Err(format!( - "Python output path '{}' is not a directory", - final_dir.display() - )); - } - copy_directory(final_dir, &stage_dir)?; +fn normalize_python_package_name(name: &str) -> String { + let mut normalized = String::with_capacity(name.len()); + for character in name.chars() { + if character.is_ascii_alphanumeric() || character == '_' { + normalized.push(character.to_ascii_lowercase()); } else { - fs::create_dir_all(&stage_dir) - .map_err(|e| format!("Failed to create {}: {}", stage_dir.display(), e))?; + normalized.push('_'); } - - Ok(Self { - final_dir: final_dir.to_path_buf(), - stage_dir, - backup_dir, - committed: false, - }) } - - fn stage_dir(&self) -> &Path { - &self.stage_dir + if normalized.is_empty() || normalized.starts_with(|character: char| character.is_ascii_digit()) + { + normalized.insert(0, '_'); } + normalized +} - fn commit(mut self) -> Result<(), String> { - let had_existing_output = self.final_dir.exists(); - if had_existing_output { - fs::rename(&self.final_dir, &self.backup_dir).map_err(|e| { - format!( - "Failed to stage existing output '{}' for replacement: {}", - self.final_dir.display(), - e - ) - })?; - } - - if let Err(error) = fs::rename(&self.stage_dir, &self.final_dir) { - if had_existing_output { - if let Err(rollback_error) = fs::rename(&self.backup_dir, &self.final_dir) { - return Err(format!( - "Failed to replace Python output directory '{}': {}. Rollback also failed: \ - {}. The original output remains at '{}'", - self.final_dir.display(), - error, - rollback_error, - self.backup_dir.display() - )); - } - } - return Err(format!( - "Failed to replace Python output directory '{}': {}", - self.final_dir.display(), - error - )); - } +/// Write content to a file with a descriptive error message on failure. +fn write_file(path: &Path, content: &str) -> Result<(), String> { + fs::write(path, content).map_err(|e| format!("Failed to write {}: {}", path.display(), e)) +} - self.committed = true; - if had_existing_output { - fs::remove_dir_all(&self.backup_dir).map_err(|e| { - format!( - "Replaced Python output but failed to remove backup '{}': {}", - self.backup_dir.display(), - e - ) - })?; - } - Ok(()) +fn print_capabilities() { + for capability in [ + "generate", + "lang.js", + "lang.py", + "input.winmd", + "input.ref", + "input.winmd-list", + "input.ref-list", + "selector.namespace-class", + ] { + println!("{}", capability); } } -impl Drop for PythonOutputTransaction { - fn drop(&mut self) { - if !self.committed && self.stage_dir.exists() { - let _ = fs::remove_dir_all(&self.stage_dir); +/// Read a list file of newline-separated .winmd paths. Trims each line and skips +/// blank lines and '#' comments. Used by --winmd-list and --ref-list to avoid +/// command-line length limits when many winmds are passed. +fn read_path_list_file(path: &str) -> Result, String> { + let content = fs::read_to_string(path) + .map_err(|e| format!("Failed to read list file '{}': {}", path, e))?; + Ok(content + .lines() + .map(|l| l.trim()) + .filter(|l| !l.is_empty() && !l.starts_with('#')) + .map(String::from) + .collect()) +} + +fn validate_winmd_paths(paths: &[String], label: &str) -> Result<(), String> { + for path in paths { + let metadata = fs::metadata(path) + .map_err(|e| format!("{} path is not accessible: {} ({})", label, path, e))?; + if !metadata.is_file() { + return Err(format!("{} path is not a file: {}", label, path)); } } + Ok(()) } -fn remove_transaction_dir(path: &Path) -> Result<(), String> { - if path.exists() { - fs::remove_dir_all(path) - .map_err(|e| format!("Failed to remove stale {}: {}", path.display(), e))?; +fn list_namespaces_for_paths(paths: &[String]) -> Vec { + if paths.is_empty() { + Vec::new() + } else { + meta::list_namespaces(&paths.join(";")) } - Ok(()) } -fn copy_directory(source: &Path, destination: &Path) -> Result<(), String> { - fs::create_dir_all(destination) - .map_err(|e| format!("Failed to create {}: {}", destination.display(), e))?; - for entry in - fs::read_dir(source).map_err(|e| format!("Failed to read {}: {}", source.display(), e))? - { - let entry = - entry.map_err(|e| format!("Failed to read entry in {}: {}", source.display(), e))?; - let source_path = entry.path(); - let destination_path = destination.join(entry.file_name()); - let file_type = entry - .file_type() - .map_err(|e| format!("Failed to inspect {}: {}", source_path.display(), e))?; - if file_type.is_dir() { - copy_directory(&source_path, &destination_path)?; - } else if file_type.is_file() { - fs::copy(&source_path, &destination_path).map_err(|e| { - format!( - "Failed to copy {} to {}: {}", - source_path.display(), - destination_path.display(), - e - ) - })?; - } else { - return Err(format!( - "Unsupported filesystem entry in Python output: {}", - source_path.display() - )); +fn has_windows_namespace(namespaces: &[String]) -> bool { + namespaces + .iter() + .any(|ns| ns == "Windows" || ns.starts_with("Windows.")) +} + +/// Find Windows SDK Windows.winmd by scanning the standard install location. +fn find_windows_sdk_winmd() -> Option { + let base = Path::new(r"C:\Program Files (x86)\Windows Kits\10\UnionMetadata"); + if !base.exists() { + return None; + } + let mut versions: Vec<_> = fs::read_dir(base) + .ok()? + .filter_map(|e| e.ok()) + .filter(|e| e.path().is_dir()) + .map(|e| e.file_name().to_string_lossy().to_string()) + .filter(|name| name.starts_with("10.")) + .collect(); + versions.sort(); + for version in versions.iter().rev() { + let winmd_path = base.join(version).join("Windows.winmd"); + if winmd_path.exists() { + return Some(winmd_path.to_string_lossy().to_string()); } } - Ok(()) + None } -fn write_python_package_manifest(output_dir: &Path, final_output_dir: &Path) -> Result<(), String> { - let manifest_path = output_dir.join("pyproject.toml"); - if manifest_path.exists() - && !python_inventory_contains(output_dir, Path::new("pyproject.toml"))? - { - return Err(format!( - "Refusing to overwrite existing non-generated manifest '{}'", - final_output_dir.join("pyproject.toml").display() - )); +#[cfg(test)] +mod tests { + use super::*; + use std::sync::atomic::{AtomicUsize, Ordering}; + + fn test_directory(name: &str) -> PathBuf { + static NEXT_ID: AtomicUsize = AtomicUsize::new(0); + std::env::temp_dir().join(format!( + "dynwinrt-codegen-{name}-{}-{}", + std::process::id(), + NEXT_ID.fetch_add(1, Ordering::Relaxed) + )) + } + + #[test] + fn com_barrel_deduplicates_only_identical_pod_factories() { + let descriptor = + "const _nativeLayout_RECT = '{\"name\":\"Windows.Win32.Foundation.RECT\"}';"; + let mut modules = BTreeMap::from([ + ( + "IFirst".into(), + BTreeSet::from(["IFirst".into(), "createRECT".into()]), + ), + ( + "ISecond".into(), + BTreeSet::from(["ISecond".into(), "createRECT".into()]), + ), + ]); + let contents = BTreeMap::from([ + ( + "IFirst".into(), + format!( + "{descriptor}\nexports.IFirst = IFirst;\nexports.createRECT = createRECT;\n" + ), + ), + ( + "ISecond".into(), + format!( + "{descriptor}\nexports.ISecond = ISecond;\nexports.createRECT = createRECT;\n" + ), + ), + ]); + + deduplicate_com_barrel_exports(&mut modules, &contents).unwrap(); + assert!(modules["IFirst"].contains("createRECT")); + assert!(!modules["ISecond"].contains("createRECT")); + + let mut conflicting_modules = modules.clone(); + conflicting_modules + .get_mut("ISecond") + .unwrap() + .insert("createRECT".into()); + let mut conflicting_contents = contents; + conflicting_contents.insert( + "ISecond".into(), + "const _nativeLayout_RECT = 'different';\nexports.createRECT = createRECT;\n".into(), + ); + assert!( + deduplicate_com_barrel_exports(&mut conflicting_modules, &conflicting_contents) + .is_err() + ); + + let union_descriptor = "const _nativeUnionLayout_VALUE = '{\"name\":\"Contoso.VALUE\"}';"; + let mut union_modules = BTreeMap::from([ + ("IFirst".into(), BTreeSet::from(["createVALUE".into()])), + ("ISecond".into(), BTreeSet::from(["createVALUE".into()])), + ]); + let union_contents = BTreeMap::from([ + ( + "IFirst".into(), + format!("{union_descriptor}\nexports.createVALUE = createVALUE;\n"), + ), + ( + "ISecond".into(), + format!("{union_descriptor}\nexports.createVALUE = createVALUE;\n"), + ), + ]); + deduplicate_com_barrel_exports(&mut union_modules, &union_contents).unwrap(); + assert!(union_modules["IFirst"].contains("createVALUE")); + assert!(!union_modules["ISecond"].contains("createVALUE")); } - let leaf = final_output_dir - .file_name() - .and_then(|name| name.to_str()) - .ok_or_else(|| { - format!( - "Cannot derive Python package name from '{}'", - final_output_dir.display() - ) - })?; - let import_name = normalize_python_package_name(leaf); - let distribution_name = import_name.replace('_', "-"); - let version = env!("CARGO_PKG_VERSION"); - let namespace_packages = collect_python_namespace_packages(output_dir)?; - let manifest = package::render_python_pyproject(&package::PythonPackageManifestInput { - distribution_name: &distribution_name, - import_name: &import_name, - package_version: version, - runtime_version: version, - namespace_packages: &namespace_packages, - }); - write_file(&manifest_path, &manifest) -} -const PYTHON_GENERATED_INVENTORY: &str = ".dynwinrt-generated-files"; -const PYTHON_TYPE_INVENTORY: &str = ".dynwinrt-generated-types"; + #[test] + fn distinct_classes_with_the_same_short_name_are_rejected() { + let classes = vec![ + meta::ClassMeta { + name: "ResourceManager".into(), + namespace: "Contoso".into(), + full_name: "Contoso.ResourceManager".into(), + ..Default::default() + }, + meta::ClassMeta { + name: "ResourceManager".into(), + namespace: "Microsoft.Windows.ApplicationModel.Resources".into(), + full_name: "Microsoft.Windows.ApplicationModel.Resources.ResourceManager".into(), + ..Default::default() + }, + ]; -fn python_inventory_contains(output_dir: &Path, relative_path: &Path) -> Result { - let inventory_path = output_dir.join(PYTHON_GENERATED_INVENTORY); - if !inventory_path.is_file() { - return Ok(false); + let error = validate_unique_class_output_names(&classes) + .expect_err("same-name classes must not overwrite each other"); + assert!(error.contains("Contoso.ResourceManager")); + assert!(error.contains("Microsoft.Windows.ApplicationModel.Resources.ResourceManager")); + assert!(error.contains("short class name `ResourceManager`")); } - Ok(fs::read_to_string(&inventory_path) - .map_err(|e| format!("Failed to read {}: {}", inventory_path.display(), e))? - .lines() - .map(Path::new) - .any(|path| path == relative_path)) -} -fn remove_all_generated_python_stubs(output_dir: &Path) -> Result<(), String> { - let inventory_path = output_dir.join(PYTHON_GENERATED_INVENTORY); - if inventory_path.is_file() { - for relative in fs::read_to_string(&inventory_path) - .map_err(|e| format!("Failed to read {}: {}", inventory_path.display(), e))? - .lines() - .map(PathBuf::from) - { - if !is_safe_relative_path(&relative) { - return Err(format!( - "Invalid path `{}` in {}", - relative.display(), - inventory_path.display() - )); - } - let is_stub = relative - .extension() - .is_some_and(|extension| extension == "pyi") - || relative.file_name().is_some_and(|name| name == "py.typed"); - let path = output_dir.join(relative); - if is_stub && path.is_file() { - fs::remove_file(&path) - .map_err(|e| format!("Failed to remove {}: {}", path.display(), e))?; - } - } - return Ok(()); - } + #[test] + fn duplicate_metadata_for_the_same_class_is_allowed() { + let class = meta::ClassMeta { + name: "Application".into(), + namespace: "Microsoft.UI.Xaml".into(), + full_name: "Microsoft.UI.Xaml.Application".into(), + ..Default::default() + }; - fn visit(current: &Path) -> Result<(), String> { - for entry in fs::read_dir(current) - .map_err(|e| format!("Failed to inspect {}: {}", current.display(), e))? - { - let entry = entry - .map_err(|e| format!("Failed to inspect entry in {}: {}", current.display(), e))?; - let path = entry.path(); - let file_type = entry - .file_type() - .map_err(|e| format!("Failed to inspect {}: {}", path.display(), e))?; - if file_type.is_dir() { - visit(&path)?; - } else if file_type.is_file() - && path.extension().is_some_and(|extension| extension == "pyi") - { - let generated = fs::read_to_string(&path) - .map_err(|e| format!("Failed to inspect {}: {}", path.display(), e))? - .starts_with("# Generated by dynwinrt-codegen"); - if generated { - fs::remove_file(&path) - .map_err(|e| format!("Failed to remove {}: {}", path.display(), e))?; - } - } - } - Ok(()) + validate_unique_class_output_names(&[class.clone(), class]) + .expect("identical metadata does not create an ambiguous output"); } - visit(output_dir) -} -fn clean_python_generated_output(output_dir: &Path) -> Result<(), String> { - let inventory_path = output_dir.join(PYTHON_GENERATED_INVENTORY); - let files = if inventory_path.is_file() { - fs::read_to_string(&inventory_path) - .map_err(|e| format!("Failed to read {}: {}", inventory_path.display(), e))? - .lines() - .map(PathBuf::from) - .collect::>() - } else { - collect_generated_python_files(output_dir, false, false)? - }; + #[cfg(windows)] + #[test] + fn generated_javascript_rejects_linked_namespace_directories() { + use std::os::windows::fs::{symlink_dir, symlink_file}; - let mut parent_dirs = HashSet::new(); - for relative in files { - if !is_safe_relative_path(&relative) { - return Err(format!( - "Invalid path `{}` in {}", - relative.display(), - inventory_path.display() - )); + let output = test_directory("javascript-linked-namespace"); + let outside = test_directory("javascript-linked-namespace-outside"); + fs::create_dir_all(&output).unwrap(); + fs::create_dir_all(&outside).unwrap(); + let link = output.join("contoso"); + if let Err(error) = symlink_dir(&outside, &link) { + eprintln!("Skipping linked-directory test: {error}"); + fs::remove_dir_all(output).unwrap(); + fs::remove_dir_all(outside).unwrap(); + return; } - let path = output_dir.join(&relative); - if path.is_file() { - fs::remove_file(&path) - .map_err(|e| format!("Failed to remove stale {}: {}", path.display(), e))?; + + let error = ensure_safe_generated_parent(&output, &link.join("Widget.js")) + .expect_err("linked namespace components must be rejected"); + + assert!(error.contains("linked directory"), "{error}"); + assert!(!outside.join("Widget.js").exists()); + fs::remove_dir(link).unwrap(); + + let external_file = outside.join("Widget.js"); + fs::write( + &external_file, + "// Generated by dynwinrt-codegen — do not edit\n", + ) + .unwrap(); + let linked_file = output.join("Widget.js"); + if symlink_file(&external_file, &linked_file).is_ok() { + let error = write_generated_javascript_file( + &output, + &linked_file, + "// Generated by dynwinrt-codegen — do not edit\nexports.Widget = Widget;\n", + ) + .expect_err("linked destination files must be rejected"); + assert!(error.contains("linked file"), "{error}"); + assert_eq!( + fs::read_to_string(&external_file).unwrap(), + "// Generated by dynwinrt-codegen — do not edit\n" + ); + fs::remove_file(linked_file).unwrap(); } - if let Some(parent) = relative.parent() { - if !parent.as_os_str().is_empty() { - parent_dirs.insert(parent.to_path_buf()); - } + let external_lifetime = outside.join("lifetime.js"); + fs::write(&external_lifetime, "outside lifetime").unwrap(); + let linked_lifetime = output.join("lifetime.js"); + if symlink_file(&external_lifetime, &linked_lifetime).is_ok() { + let error = + write_lifetime_module(&output).expect_err("linked root artifacts must be rejected"); + assert!(error.contains("linked file"), "{error}"); + assert_eq!( + fs::read_to_string(&external_lifetime).unwrap(), + "outside lifetime" + ); + fs::remove_file(linked_lifetime).unwrap(); } + fs::remove_dir_all(output).unwrap(); + fs::remove_dir_all(outside).unwrap(); } - if inventory_path.is_file() { - fs::remove_file(&inventory_path) - .map_err(|e| format!("Failed to remove {}: {}", inventory_path.display(), e))?; + + #[test] + fn javascript_namespace_layout_emits_canonical_modules_and_qualified_root_exports() { + let class = |namespace: &str, iid: &str| meta::ClassMeta { + name: "Widget".into(), + namespace: namespace.into(), + full_name: format!("{namespace}.Widget"), + default_interface: Some(meta::InterfaceMeta { + name: "IWidget".into(), + namespace: namespace.into(), + iid: iid.into(), + methods: vec![meta::MethodMeta { + name: "GetPoint".into(), + return_type: Some(TypeMeta::Struct { + namespace: "Windows.Foundation".into(), + name: "Point".into(), + fields: vec![ + dynwinrt_codegen::types::FieldMeta { + name: "X".into(), + typ: TypeMeta::F32, + }, + dynwinrt_codegen::types::FieldMeta { + name: "Y".into(), + typ: TypeMeta::F32, + }, + ], + }), + ..Default::default() + }], + ..Default::default() + }), + ..Default::default() + }; + let mut classes = vec![ + class("Contoso.Alpha", "11111111-1111-1111-1111-111111111111"), + class("Fabrikam.Beta", "22222222-2222-2222-2222-222222222222"), + ]; + let records = javascript_type_layout_records(&classes, &[], &[]).unwrap(); + let identities = records.iter().map(|record| record.identity.clone()); + let _layout = javascript::install_javascript_module_layout(identities).unwrap(); + javascript::apply_javascript_projected_names(&mut classes, &mut [], &mut []); + let known_types = classes + .iter() + .map(|class| class.name.clone()) + .collect::>(); + let output = test_directory("javascript-namespace-layout"); + fs::create_dir_all(&output).unwrap(); + + generate_js_files( + &output, + &classes, + &[], + &[], + &[], + &known_types, + &HashSet::new(), + &HashSet::new(), + &HashMap::new(), + &HashMap::new(), + &HashMap::new(), + ) + .unwrap(); + write_javascript_type_inventory( + &output, + &emitted_javascript_type_records(&output, &[], &records).unwrap(), + ) + .unwrap(); + write_js_barrel_and_manifest(&output, "").unwrap(); + + assert!(output.join("contoso/alpha/Widget.js").is_file()); + assert!(output.join("fabrikam/beta/Widget.js").is_file()); + assert!(!output.join("ContosoAlphaWidget.js").exists()); + assert!(!output.join("FabrikamBetaWidget.js").exists()); + assert!(!output.join("Widget.js").exists()); + let index = fs::read_to_string(output.join("index.d.ts")).unwrap(); + assert!(index.contains("ContosoAlphaWidget")); + assert!(index.contains("FabrikamBetaWidget")); + assert!(index.contains("packPoint")); + let package = fs::read_to_string(output.join("package.json")).unwrap(); + assert!(!package.contains("\"./ContosoAlphaWidget\"")); + assert!(package.contains("\"./contoso/alpha/Widget\"")); + + fs::remove_dir_all(output).unwrap(); } - let type_inventory = output_dir.join(PYTHON_TYPE_INVENTORY); - if type_inventory.is_file() { - fs::remove_file(&type_inventory) - .map_err(|e| format!("Failed to remove {}: {}", type_inventory.display(), e))?; + + #[test] + fn legacy_javascript_output_requires_one_time_clean_regeneration() { + let output = test_directory("javascript-legacy-layout"); + fs::create_dir_all(&output).unwrap(); + fs::write( + output.join("Widget.js"), + "// Generated by dynwinrt-codegen — do not edit\nexports.Widget = Widget;\n", + ) + .unwrap(); + + let error = ensure_javascript_layout_inventory(&output) + .expect_err("legacy generated files without identities must fail closed"); + + assert!(error.contains("legacy flat layout"), "{error}"); + assert!(error.contains("regenerate it once"), "{error}"); + assert!(output.join("Widget.js").is_file()); + fs::remove_dir_all(output).unwrap(); } - let mut parent_dirs = parent_dirs.into_iter().collect::>(); - parent_dirs.sort_by_key(|path| std::cmp::Reverse(path.components().count())); - for relative in parent_dirs { - let path = output_dir.join(relative); - if path.is_dir() { - match fs::remove_dir(&path) { - Ok(()) => {} - Err(error) if error.kind() == std::io::ErrorKind::DirectoryNotEmpty => {} - Err(error) => { - return Err(format!( - "Failed to remove stale package directory {}: {}", - path.display(), - error - )); - } - } + #[test] + fn generated_struct_helper_scan_rejects_cross_module_identity_collisions() { + let identities = [ + javascript::JavaScriptTypeIdentity::new( + "Contoso.Alpha", + "First", + javascript::JavaScriptTypeKind::Class, + ), + javascript::JavaScriptTypeIdentity::new( + "Contoso.Beta", + "Second", + javascript::JavaScriptTypeKind::Class, + ), + ]; + let _layout = javascript::install_javascript_module_layout(identities).unwrap(); + let output = test_directory("javascript-cross-module-struct-helper"); + for (module, struct_identity) in [ + ("contoso/alpha/First", "Alpha.Payload"), + ("contoso/beta/Second", "Beta.Payload"), + ] { + let path = output.join(format!("{module}.js")); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write( + path, + format!( + "// Generated by dynwinrt-codegen — do not edit\n\ + const Payload_Type = DynWinRtType.structType('{struct_identity}', []);\n" + ), + ) + .unwrap(); } + + let error = validate_generated_struct_helper_identities(&output) + .expect_err("cross-module helper identity collision must fail closed"); + + assert!(error.contains("Alpha.Payload"), "{error}"); + assert!(error.contains("Beta.Payload"), "{error}"); + assert!(error.contains("packPayload"), "{error}"); + fs::remove_dir_all(output).unwrap(); + } + + #[test] + fn retained_projected_type_adds_new_module_alias_without_regeneration() { + let windows = javascript::JavaScriptTypeIdentity::new( + "Windows.Foundation", + "Widget", + javascript::JavaScriptTypeKind::Class, + ); + let contoso = javascript::JavaScriptTypeIdentity::new( + "Contoso", + "Widget", + javascript::JavaScriptTypeKind::Class, + ); + let old_layout = + javascript::install_javascript_module_layout([windows.clone(), contoso.clone()]) + .unwrap(); + let previous = javascript::javascript_output_targets() + .into_iter() + .find(|target| target.identity == windows) + .map(|target| { + javascript::JavaScriptTypeLayoutRecord::new( + target.identity, + target.projected_name, + "type", + ) + }) + .unwrap(); + drop(old_layout); + let _layout = javascript::install_javascript_module_layout_with_records( + [ + windows.clone(), + contoso, + javascript::JavaScriptTypeIdentity::new( + "Microsoft.UI.Foundation", + "Widget", + javascript::JavaScriptTypeKind::Class, + ), + ], + [previous.clone()], + ) + .unwrap(); + let output = test_directory("javascript-retained-projected-alias"); + let js = output.join("windows/foundation/Widget.js"); + let dts = output.join("windows/foundation/Widget.d.ts"); + fs::create_dir_all(js.parent().unwrap()).unwrap(); + fs::write( + &js, + "// Generated by dynwinrt-codegen — do not edit\nexports.FoundationWidget = FoundationWidget;\n", + ) + .unwrap(); + fs::write( + &dts, + "// Generated by dynwinrt-codegen — do not edit\nexport class FoundationWidget {}\n", + ) + .unwrap(); + + write_retained_javascript_projected_aliases(&output, &[previous]).unwrap(); + + assert!( + fs::read_to_string(&js) + .unwrap() + .contains("exports.WindowsFoundationWidgetClass = exports.FoundationWidget;") + ); + assert!( + fs::read_to_string(&dts) + .unwrap() + .contains("export { FoundationWidget as WindowsFoundationWidgetClass };") + ); + fs::remove_dir_all(output).unwrap(); + } + + #[test] + fn repeated_retained_renames_alias_the_original_implementation() { + let contoso = javascript::JavaScriptTypeIdentity::new( + "Contoso", + "Widget", + javascript::JavaScriptTypeKind::Class, + ); + let previous = + javascript::JavaScriptTypeLayoutRecord::new(contoso.clone(), "ContosoWidget", "type") + .with_implementation_name("Widget"); + let _layout = javascript::install_javascript_module_layout_with_records( + [ + contoso, + javascript::JavaScriptTypeIdentity::new( + "Aardvark", + "Widget", + javascript::JavaScriptTypeKind::Class, + ), + javascript::JavaScriptTypeIdentity::new( + "Con.Toso", + "Widget", + javascript::JavaScriptTypeKind::Class, + ), + ], + [previous.clone()], + ) + .unwrap(); + let output = test_directory("javascript-repeated-retained-alias"); + let js = output.join("contoso/Widget.js"); + let dts = output.join("contoso/Widget.d.ts"); + fs::create_dir_all(js.parent().unwrap()).unwrap(); + fs::write( + &js, + "// Generated by dynwinrt-codegen — do not edit\n\ + class Widget {}\n\ + exports.Widget = Widget;\n\ + exports.ContosoWidget = Widget;\n", + ) + .unwrap(); + fs::write( + &dts, + "// Generated by dynwinrt-codegen — do not edit\n\ + export declare class Widget {}\n\ + export { Widget as ContosoWidget };\n", + ) + .unwrap(); + + write_retained_javascript_projected_aliases(&output, &[previous]).unwrap(); + + let js = fs::read_to_string(js).unwrap(); + let dts = fs::read_to_string(dts).unwrap(); + assert!( + js.contains("exports.ContosoWidgetClass = exports.Widget;"), + "{js}" + ); + assert!( + dts.contains("export { Widget as ContosoWidgetClass };"), + "{dts}" + ); + assert!( + !dts.contains("export { ContosoWidget as ContosoWidgetClass };"), + "{dts}" + ); + fs::remove_dir_all(output).unwrap(); } - Ok(()) -} -fn write_python_generated_inventory(output_dir: &Path, pyi: bool) -> Result<(), String> { - let files = collect_generated_python_files(output_dir, true, pyi)?; - let content = files - .iter() - .map(|path| path.to_string_lossy()) - .collect::>() - .join("\n"); - write_file( - &output_dir.join(PYTHON_GENERATED_INVENTORY), - &format!("{content}\n"), - ) -} + #[test] + fn retained_name_cycle_does_not_emit_a_self_alias() { + let identity = javascript::JavaScriptTypeIdentity::new( + "Contoso", + "Widget", + javascript::JavaScriptTypeKind::Class, + ); + let previous = + javascript::JavaScriptTypeLayoutRecord::new(identity.clone(), "ContosoWidget", "type") + .with_implementation_name("Widget"); + let _layout = javascript::install_javascript_module_layout_with_records( + [identity], + [previous.clone()], + ) + .unwrap(); + let output = test_directory("javascript-retained-name-cycle"); + let js = output.join("contoso/Widget.js"); + let dts = output.join("contoso/Widget.d.ts"); + fs::create_dir_all(js.parent().unwrap()).unwrap(); + fs::write( + &js, + "// Generated by dynwinrt-codegen — do not edit\nexports.Widget = Widget;\n", + ) + .unwrap(); + fs::write( + &dts, + "// Generated by dynwinrt-codegen — do not edit\nexport class Widget {}\n", + ) + .unwrap(); -fn collect_generated_python_files( - output_dir: &Path, - include_root_manifest: bool, - include_root_marker: bool, -) -> Result, String> { - fn visit( - root: &Path, - current: &Path, - include_root_manifest: bool, - include_root_marker: bool, - files: &mut Vec, - ) -> Result<(), String> { - for entry in fs::read_dir(current) - .map_err(|e| format!("Failed to inspect {}: {}", current.display(), e))? - { - let entry = entry - .map_err(|e| format!("Failed to inspect entry in {}: {}", current.display(), e))?; - let path = entry.path(); - let file_type = entry - .file_type() - .map_err(|e| format!("Failed to inspect {}: {}", path.display(), e))?; - if file_type.is_dir() { - visit( - root, - &path, - include_root_manifest, - include_root_marker, - files, - )?; - continue; - } - if !file_type.is_file() || entry.file_name() == PYTHON_GENERATED_INVENTORY { - continue; - } + write_retained_javascript_projected_aliases(&output, &[previous]).unwrap(); - let generated = match entry.file_name().to_str() { - Some("py.typed") => include_root_marker && current == root, - Some("pyproject.toml") => include_root_manifest && current == root, - Some(name) if name.ends_with(".py") || name.ends_with(".pyi") => { - fs::read_to_string(&path) - .map_err(|e| format!("Failed to inspect {}: {}", path.display(), e))? - .starts_with("# Generated by dynwinrt-codegen") - } - _ => false, - }; - if generated { - files.push(path.strip_prefix(root).unwrap().to_path_buf()); - } - } - Ok(()) + assert!( + !fs::read_to_string(js) + .unwrap() + .contains("exports.Widget = exports.Widget") + ); + assert!( + !fs::read_to_string(dts) + .unwrap() + .contains("export { Widget as Widget }") + ); + fs::remove_dir_all(output).unwrap(); } - let mut files = Vec::new(); - visit( - output_dir, - output_dir, - include_root_manifest, - include_root_marker, - &mut files, - )?; - files.sort(); - Ok(files) -} + #[test] + fn com_subtree_does_not_trigger_legacy_winrt_detection() { + let output = test_directory("javascript-ignore-com-subtree"); + fs::create_dir_all(output.join("com")).unwrap(); + fs::write( + output.join("com").join("IWidget.js"), + "// Generated by dynwinrt-codegen - do not edit\nexports.IWidget = IWidget;\n", + ) + .unwrap(); -fn is_safe_relative_path(path: &Path) -> bool { - !path.as_os_str().is_empty() - && path - .components() - .all(|component| matches!(component, std::path::Component::Normal(_))) -} + check_javascript_layout_inventory(&output) + .expect("Classic COM modules are isolated from WinRT inventory detection"); -fn collect_python_namespace_packages(output_dir: &Path) -> Result, String> { - fn visit(root: &Path, current: &Path, packages: &mut Vec) -> Result<(), String> { - for entry in fs::read_dir(current) - .map_err(|e| format!("Failed to inspect {}: {}", current.display(), e))? - { - let entry = entry - .map_err(|e| format!("Failed to inspect entry in {}: {}", current.display(), e))?; - if !entry - .file_type() - .map_err(|e| format!("Failed to inspect {}: {}", entry.path().display(), e))? - .is_dir() - { - continue; - } - let path = entry.path(); - if path.join("__init__.py").is_file() { - let relative = path.strip_prefix(root).map_err(|e| { - format!("Failed to normalize package path {}: {}", path.display(), e) - })?; - packages.push( - relative - .components() - .map(|component| component.as_os_str().to_string_lossy()) - .collect::>() - .join("."), - ); - } - visit(root, &path, packages)?; - } - Ok(()) + fs::remove_dir_all(output).unwrap(); } - let mut packages = Vec::new(); - visit(output_dir, output_dir, &mut packages)?; - packages.sort(); - Ok(packages) -} + #[test] + fn uninventoried_canonical_targets_fail_closed() { + let output = test_directory("javascript-uninventoried-canonical"); + let canonical = output.join("contoso").join("Widget.js"); + fs::create_dir_all(canonical.parent().unwrap()).unwrap(); + fs::write( + &canonical, + "// Generated by dynwinrt-codegen — do not edit\nexports.Widget = Widget;\n", + ) + .unwrap(); + let identity = javascript::JavaScriptTypeIdentity::new( + "Contoso", + "Widget", + javascript::JavaScriptTypeKind::Class, + ); + let _layout = javascript::install_javascript_module_layout([identity]).unwrap(); -fn normalize_python_package_name(name: &str) -> String { - let mut normalized = String::with_capacity(name.len()); - for character in name.chars() { - if character.is_ascii_alphanumeric() || character == '_' { - normalized.push(character.to_ascii_lowercase()); - } else { - normalized.push('_'); - } - } - if normalized.is_empty() || normalized.starts_with(|character: char| character.is_ascii_digit()) - { - normalized.insert(0, '_'); + let error = ensure_uninventoried_javascript_targets_absent(&output) + .expect_err("canonical output without inventory must fail closed"); + + assert!(error.contains("has no type inventory"), "{error}"); + assert!(canonical.is_file()); + fs::remove_dir_all(output).unwrap(); } - normalized -} -/// Write content to a file with a descriptive error message on failure. -fn write_file(path: &Path, content: &str) -> Result<(), String> { - fs::write(path, content).map_err(|e| format!("Failed to write {}: {}", path.display(), e)) -} + #[test] + fn colliding_empty_class_stubs_keep_native_canonical_aliases() { + let mut classes = vec![ + meta::ClassMeta { + name: "Widget".into(), + namespace: "Contoso.Alpha".into(), + full_name: "Contoso.Alpha.Widget".into(), + ..Default::default() + }, + meta::ClassMeta { + name: "Widget".into(), + namespace: "Fabrikam.Beta".into(), + full_name: "Fabrikam.Beta.Widget".into(), + ..Default::default() + }, + ]; + let identities = javascript_type_identities(&classes, &[], &[]).unwrap(); + let _layout = javascript::install_javascript_module_layout(identities).unwrap(); + javascript::apply_javascript_projected_names(&mut classes, &mut [], &mut []); + let known_types = classes + .iter() + .map(|class| class.name.clone()) + .collect::>(); + let output = test_directory("javascript-colliding-stubs"); + fs::create_dir_all(&output).unwrap(); -fn print_capabilities() { - for capability in [ - "generate", - "lang.js", - "lang.py", - "input.winmd", - "input.ref", - "input.winmd-list", - "input.ref-list", - "selector.namespace-class", - ] { - println!("{}", capability); + generate_js_files( + &output, + &classes, + &[], + &[], + &[], + &known_types, + &HashSet::new(), + &HashSet::new(), + &HashMap::new(), + &HashMap::new(), + &HashMap::new(), + ) + .unwrap(); + + let js = fs::read_to_string(output.join("contoso/alpha/Widget.js")).unwrap(); + assert!(js.contains("exports.Widget = ContosoAlphaWidget;"), "{js}"); + let dts = fs::read_to_string(output.join("contoso/alpha/Widget.d.ts")).unwrap(); + assert!( + dts.contains("export { ContosoAlphaWidget as Widget };"), + "{dts}" + ); + fs::remove_dir_all(output).unwrap(); } -} -/// Read a list file of newline-separated .winmd paths. Trims each line and skips -/// blank lines and '#' comments. Used by --winmd-list and --ref-list to avoid -/// command-line length limits when many winmds are passed. -fn read_path_list_file(path: &str) -> Result, String> { - let content = fs::read_to_string(path) - .map_err(|e| format!("Failed to read list file '{}': {}", path, e))?; - Ok(content - .lines() - .map(|l| l.trim()) - .filter(|l| !l.is_empty() && !l.starts_with('#')) - .map(String::from) - .collect()) -} + #[test] + fn javascript_inventory_uses_initial_schema_version() { + let output = test_directory("javascript-inventory-version"); + fs::create_dir_all(&output).unwrap(); + write_javascript_type_inventory(&output, &[]).unwrap(); -fn validate_winmd_paths(paths: &[String], label: &str) -> Result<(), String> { - for path in paths { - let metadata = fs::metadata(path) - .map_err(|e| format!("{} path is not accessible: {} ({})", label, path, e))?; - if !metadata.is_file() { - return Err(format!("{} path is not a file: {}", label, path)); - } + let content = fs::read_to_string(output.join(JAVASCRIPT_TYPE_INVENTORY)).unwrap(); + let inventory: serde_json::Value = serde_json::from_str(&content).unwrap(); + + assert_eq!(inventory["version"], 1); + fs::remove_dir_all(output).unwrap(); } - Ok(()) -} -fn list_namespaces_for_paths(paths: &[String]) -> Vec { - if paths.is_empty() { - Vec::new() - } else { - meta::list_namespaces(&paths.join(";")) + #[test] + fn truncated_javascript_inventory_is_rejected() { + let output = test_directory("javascript-truncated-inventory"); + let canonical = output.join("contoso").join("Widget.js"); + fs::create_dir_all(canonical.parent().unwrap()).unwrap(); + fs::write( + &canonical, + "// Generated by dynwinrt-codegen — do not edit\nexports.Widget = Widget;\n", + ) + .unwrap(); + write_javascript_type_inventory(&output, &[]).unwrap(); + + let error = read_javascript_type_inventory(&output) + .expect_err("inventory missing an existing canonical type must fail closed"); + + assert!(error.contains("does not match"), "{error}"); + assert!(canonical.is_file()); + fs::remove_dir_all(output).unwrap(); } -} -fn has_windows_namespace(namespaces: &[String]) -> bool { - namespaces - .iter() - .any(|ns| ns == "Windows" || ns.starts_with("Windows.")) -} + #[test] + fn javascript_namespace_layout_handles_colliding_delegates_without_flat_files() { + let delegate = |namespace: &str, iid: &str| meta::InterfaceMeta { + name: "Handler".into(), + namespace: namespace.into(), + iid: iid.into(), + methods: vec![ + meta::MethodMeta { + name: ".ctor".into(), + ..Default::default() + }, + meta::MethodMeta { + name: "Invoke".into(), + return_type: Some(TypeMeta::Object), + ..Default::default() + }, + ], + ..Default::default() + }; + let mut interfaces = vec![ + delegate("Contoso.Alpha", "11111111-1111-1111-1111-111111111111"), + delegate("Fabrikam.Beta", "22222222-2222-2222-2222-222222222222"), + ]; + let identities = javascript_type_identities(&[], &interfaces, &[]).unwrap(); + let _layout = javascript::install_javascript_module_layout(identities).unwrap(); + javascript::apply_javascript_projected_names(&mut [], &mut interfaces, &mut []); + let delegate_names = interfaces + .iter() + .map(|interface| interface.name.clone()) + .collect::>(); + let (signatures, references, wraps) = + project::build_delegate_signatures(&interfaces, &delegate_names, &delegate_names); + let output = test_directory("javascript-delegate-layout"); + fs::create_dir_all(&output).unwrap(); + + generate_js_files( + &output, + &[], + &interfaces, + &[], + &[], + &delegate_names, + &delegate_names, + &HashSet::new(), + &signatures, + &references, + &wraps, + ) + .unwrap(); -/// Find Windows SDK Windows.winmd by scanning the standard install location. -fn find_windows_sdk_winmd() -> Option { - let base = Path::new(r"C:\Program Files (x86)\Windows Kits\10\UnionMetadata"); - if !base.exists() { - return None; - } - let mut versions: Vec<_> = fs::read_dir(base) - .ok()? - .filter_map(|e| e.ok()) - .filter(|e| e.path().is_dir()) - .map(|e| e.file_name().to_string_lossy().to_string()) - .filter(|name| name.starts_with("10.")) - .collect(); - versions.sort(); - for version in versions.iter().rev() { - let winmd_path = base.join(version).join("Windows.winmd"); - if winmd_path.exists() { - return Some(winmd_path.to_string_lossy().to_string()); + for name in ["ContosoAlphaHandler", "FabrikamBetaHandler"] { + assert!(!output.join(format!("{name}.js")).exists()); } - } - None -} - -#[cfg(test)] -mod tests { - use super::*; - use std::sync::atomic::{AtomicUsize, Ordering}; + let contoso = fs::read_to_string(output.join("contoso/alpha/Handler.d.ts")).unwrap(); + assert!(contoso.contains("export type ContosoAlphaHandler")); + assert!(contoso.contains("export type Handler = ContosoAlphaHandler")); - fn test_directory(name: &str) -> PathBuf { - static NEXT_ID: AtomicUsize = AtomicUsize::new(0); - std::env::temp_dir().join(format!( - "dynwinrt-codegen-{name}-{}-{}", - std::process::id(), - NEXT_ID.fetch_add(1, Ordering::Relaxed) - )) + fs::remove_dir_all(output).unwrap(); } #[test] - fn com_barrel_deduplicates_only_identical_pod_factories() { - let descriptor = - "const _nativeLayout_RECT = '{\"name\":\"Windows.Win32.Foundation.RECT\"}';"; - let mut modules = BTreeMap::from([ - ( - "IFirst".into(), - BTreeSet::from(["IFirst".into(), "createRECT".into()]), - ), - ( - "ISecond".into(), - BTreeSet::from(["ISecond".into(), "createRECT".into()]), - ), - ]); - let contents = BTreeMap::from([ - ( - "IFirst".into(), - format!( - "{descriptor}\nexports.IFirst = IFirst;\nexports.createRECT = createRECT;\n" - ), - ), - ( - "ISecond".into(), - format!( - "{descriptor}\nexports.ISecond = ISecond;\nexports.createRECT = createRECT;\n" - ), - ), - ]); + fn colliding_interfaces_preserve_native_iid_exports() { + let interface = |namespace: &str, iid: &str| meta::InterfaceMeta { + name: "IWidget".into(), + namespace: namespace.into(), + iid: iid.into(), + methods: vec![meta::MethodMeta { + name: "GetValue".into(), + return_type: Some(TypeMeta::I32), + ..Default::default() + }], + ..Default::default() + }; + let mut interfaces = vec![ + interface("Contoso.Alpha", "11111111-1111-1111-1111-111111111111"), + interface("Fabrikam.Beta", "22222222-2222-2222-2222-222222222222"), + ]; + let identities = javascript_type_identities(&[], &interfaces, &[]).unwrap(); + let _layout = javascript::install_javascript_module_layout(identities).unwrap(); + javascript::apply_javascript_projected_names(&mut [], &mut interfaces, &mut []); + let known_types = interfaces + .iter() + .map(|interface| interface.name.clone()) + .collect::>(); + let output = test_directory("javascript-interface-iid-aliases"); + fs::create_dir_all(&output).unwrap(); - deduplicate_com_barrel_exports(&mut modules, &contents).unwrap(); - assert!(modules["IFirst"].contains("createRECT")); - assert!(!modules["ISecond"].contains("createRECT")); + generate_js_files( + &output, + &[], + &interfaces, + &[], + &[], + &known_types, + &HashSet::new(), + &HashSet::new(), + &HashMap::new(), + &HashMap::new(), + &HashMap::new(), + ) + .unwrap(); - let mut conflicting_modules = modules.clone(); - conflicting_modules - .get_mut("ISecond") - .unwrap() - .insert("createRECT".into()); - let mut conflicting_contents = contents; - conflicting_contents.insert( - "ISecond".into(), - "const _nativeLayout_RECT = 'different';\nexports.createRECT = createRECT;\n".into(), + let js = fs::read_to_string(output.join("contoso/alpha/IWidget.js")).unwrap(); + assert!(js.contains("exports.IID_ContosoAlphaIWidget ="), "{js}"); + assert!( + js.contains("exports.IID_IWidget = exports.IID_ContosoAlphaIWidget"), + "{js}" ); + let dts = fs::read_to_string(output.join("contoso/alpha/IWidget.d.ts")).unwrap(); assert!( - deduplicate_com_barrel_exports(&mut conflicting_modules, &conflicting_contents) - .is_err() + dts.contains("IID_ContosoAlphaIWidget as IID_IWidget"), + "{dts}" + ); + assert_eq!( + dts.matches("export { ContosoAlphaIWidget as IWidget };") + .count(), + 1, + "{dts}" ); - let union_descriptor = "const _nativeUnionLayout_VALUE = '{\"name\":\"Contoso.VALUE\"}';"; - let mut union_modules = BTreeMap::from([ - ("IFirst".into(), BTreeSet::from(["createVALUE".into()])), - ("ISecond".into(), BTreeSet::from(["createVALUE".into()])), - ]); - let union_contents = BTreeMap::from([ - ( - "IFirst".into(), - format!("{union_descriptor}\nexports.createVALUE = createVALUE;\n"), - ), - ( - "ISecond".into(), - format!("{union_descriptor}\nexports.createVALUE = createVALUE;\n"), - ), - ]); - deduplicate_com_barrel_exports(&mut union_modules, &union_contents).unwrap(); - assert!(union_modules["IFirst"].contains("createVALUE")); - assert!(!union_modules["ISecond"].contains("createVALUE")); + fs::remove_dir_all(output).unwrap(); } #[test] - fn distinct_classes_with_the_same_short_name_are_rejected() { - let classes = vec![ - meta::ClassMeta { - name: "ResourceManager".into(), + fn collision_renamed_iclosable_uses_projected_import() { + let closable = meta::InterfaceMeta { + name: "IClosable".into(), + namespace: "Windows.Foundation".into(), + iid: "30d5a829-7fa4-4026-83bb-d75bae4ea99e".into(), + methods: vec![meta::MethodMeta { + name: "Close".into(), + ..Default::default() + }], + ..Default::default() + }; + let mut classes = vec![meta::ClassMeta { + name: "Resource".into(), + namespace: "Contoso".into(), + full_name: "Contoso.Resource".into(), + default_interface: Some(meta::InterfaceMeta { + name: "IResource".into(), namespace: "Contoso".into(), - full_name: "Contoso.ResourceManager".into(), + iid: "11111111-1111-1111-1111-111111111111".into(), + ..Default::default() + }), + required_interfaces: vec![closable.clone()], + ..Default::default() + }]; + let mut interfaces = vec![ + closable, + meta::InterfaceMeta { + name: "IClosable".into(), + namespace: "Contoso".into(), + iid: "22222222-2222-2222-2222-222222222222".into(), ..Default::default() }, - meta::ClassMeta { - name: "ResourceManager".into(), - namespace: "Microsoft.Windows.ApplicationModel.Resources".into(), - full_name: "Microsoft.Windows.ApplicationModel.Resources.ResourceManager".into(), + ]; + let identities = javascript_type_identities(&classes, &interfaces, &[]).unwrap(); + let _layout = javascript::install_javascript_module_layout(identities).unwrap(); + javascript::apply_javascript_projected_names(&mut classes, &mut interfaces, &mut []); + let projected_closable = classes[0].required_interfaces[0].name.clone(); + assert_ne!(projected_closable, "IClosable"); + let known = HashSet::from([ + classes[0].name.clone(), + projected_closable.clone(), + interfaces[1].name.clone(), + ]); + let projected = project::project_class( + &classes[0], + &known, + &HashSet::new(), + &HashSet::new(), + &HashMap::new(), + &HashMap::new(), + &HashMap::new(), + ); + let js = render_js::render(&projected); + + assert!( + js.contains(&format!("__get_{projected_closable}()")), + "{js}" + ); + assert!(!js.contains("__get_IClosable()"), "{js}"); + } + + #[test] + fn collision_renamed_element_factory_keeps_special_projection() { + let mut interfaces = vec![ + meta::InterfaceMeta { + name: "IElementFactory".into(), + namespace: "Microsoft.UI.Xaml".into(), + iid: "11111111-1111-1111-1111-111111111111".into(), + ..Default::default() + }, + meta::InterfaceMeta { + name: "IElementFactory".into(), + namespace: "Contoso".into(), + iid: "22222222-2222-2222-2222-222222222222".into(), ..Default::default() }, ]; + let identities = javascript_type_identities(&[], &interfaces, &[]).unwrap(); + let _layout = javascript::install_javascript_module_layout(identities).unwrap(); + javascript::apply_javascript_projected_names(&mut [], &mut interfaces, &mut []); + let known = interfaces + .iter() + .map(|interface| interface.name.clone()) + .collect::>(); + let projected = project::project_interface( + &interfaces[0], + &known, + &HashSet::new(), + &HashMap::new(), + &HashMap::new(), + &HashMap::new(), + ); + let dts = render_dts::render(&projected); - let error = validate_unique_class_output_names(&classes) - .expect_err("same-name classes must not overwrite each other"); - assert!(error.contains("Contoso.ResourceManager")); - assert!(error.contains("Microsoft.Windows.ApplicationModel.Resources.ResourceManager")); - assert!(error.contains("short class name `ResourceManager`")); + assert_ne!(interfaces[0].name, "IElementFactory"); + assert!(dts.contains("static create(getElement:"), "{dts}"); } #[test] - fn duplicate_metadata_for_the_same_class_is_allowed() { - let class = meta::ClassMeta { - name: "Application".into(), - namespace: "Microsoft.UI.Xaml".into(), - full_name: "Microsoft.UI.Xaml.Application".into(), + fn closed_generics_use_complete_argument_identity() { + let interface = |argument_namespace: &str, iid: &str| meta::InterfaceMeta { + name: "IVector_Widget".into(), + namespace: "Windows.Foundation.Collections".into(), + iid: iid.into(), + generic_piid: Some(meta::PIID_IVECTOR.into()), + generic_args: vec![TypeMeta::RuntimeClass { + namespace: argument_namespace.into(), + name: "Widget".into(), + default_interface: None, + }], ..Default::default() }; + let first = interface("Contoso.Alpha", meta::PIID_IVECTOR); + let second = interface("Fabrikam.Beta", meta::PIID_IVECTOR); + let first_records = + javascript_type_layout_records(&[], std::slice::from_ref(&first), &[]).unwrap(); + let second_records = + javascript_type_layout_records(&[], std::slice::from_ref(&second), &[]).unwrap(); + let first_name = javascript::parameterized_interface_name( + &first.namespace, + &first.name, + first.generic_piid.as_deref().unwrap(), + &first.generic_args, + ); + let second_name = javascript::parameterized_interface_name( + &second.namespace, + &second.name, + second.generic_piid.as_deref().unwrap(), + &second.generic_args, + ); - validate_unique_class_output_names(&[class.clone(), class]) - .expect("identical metadata does not create an ambiguous output"); + assert_eq!(first_records[0].identity.name, first_name); + assert_eq!(second_records[0].identity.name, second_name); + assert_ne!(first_name, second_name); + validate_javascript_type_layout_records(&first_records, &second_records) + .expect("incremental generic identities must coexist"); + + let mut interfaces = vec![first, second]; + let same_run_records = javascript_type_layout_records(&[], &interfaces, &[]).unwrap(); + validate_javascript_type_layout_records(&[], &same_run_records) + .expect("same-run generic identities must coexist"); + let _layout = javascript::install_javascript_module_layout_with_records( + same_run_records + .iter() + .map(|record| record.identity.clone()), + same_run_records.iter().cloned(), + ) + .unwrap(); + let modules = javascript::javascript_output_targets() + .into_iter() + .map(|target| target.canonical_module) + .collect::>(); + assert!(modules.contains(&format!("windows/foundation/collections/{first_name}"))); + assert!(modules.contains(&format!("windows/foundation/collections/{second_name}"))); + + javascript::apply_javascript_projected_names(&mut [], &mut interfaces, &mut []); + assert_eq!(interfaces[0].name, first_name); + assert_eq!(interfaces[1].name, second_name); + let known_types = interfaces + .iter() + .map(|interface| interface.name.clone()) + .collect::>(); + let output = test_directory("javascript-complete-generic-identities"); + fs::create_dir_all(&output).unwrap(); + generate_js_files( + &output, + &[], + &interfaces, + &[], + &[], + &known_types, + &HashSet::new(), + &HashSet::new(), + &HashMap::new(), + &HashMap::new(), + &HashMap::new(), + ) + .unwrap(); + assert!( + output + .join(format!("windows/foundation/collections/{first_name}.js")) + .is_file() + ); + assert!( + output + .join(format!("windows/foundation/collections/{second_name}.js")) + .is_file() + ); + fs::remove_dir_all(output).unwrap(); } #[test] @@ -3800,12 +6061,12 @@ mod tests { } #[test] - fn python_output_transaction_commits_complete_tree() { + fn output_transaction_commits_complete_tree() { let output = test_directory("transaction-commit"); fs::create_dir_all(&output).unwrap(); fs::write(output.join("existing.py"), "old").unwrap(); - let transaction = PythonOutputTransaction::begin(&output).unwrap(); + let transaction = OutputTransaction::begin(&output).unwrap(); fs::write(transaction.stage_dir().join("existing.py"), "new").unwrap(); fs::write(transaction.stage_dir().join("added.py"), "added").unwrap(); transaction.commit().unwrap(); @@ -3821,6 +6082,127 @@ mod tests { fs::remove_dir_all(output).unwrap(); } + #[test] + fn output_transaction_preserves_unrelated_legacy_backup_directory() { + let output = test_directory("transaction-unrelated-backup"); + fs::create_dir_all(&output).unwrap(); + fs::write(output.join("existing.js"), "original").unwrap(); + let parent = output.parent().unwrap(); + let leaf = output.file_name().unwrap().to_string_lossy(); + let backup = parent.join(format!(".{leaf}.dynwinrt-backup")); + fs::create_dir_all(&backup).unwrap(); + fs::write(backup.join("unrelated.txt"), "keep").unwrap(); + + let transaction = OutputTransaction::begin(&output).unwrap(); + fs::write(transaction.stage_dir().join("existing.js"), "updated").unwrap(); + transaction.commit().unwrap(); + + assert_eq!( + fs::read_to_string(output.join("existing.js")).unwrap(), + "updated" + ); + assert_eq!( + fs::read_to_string(backup.join("unrelated.txt")).unwrap(), + "keep" + ); + fs::remove_dir_all(output).unwrap(); + fs::remove_dir_all(backup).unwrap(); + } + + #[test] + fn output_transaction_refuses_orphaned_nonce_artifacts() { + let output = test_directory("transaction-orphan"); + fs::create_dir_all(&output).unwrap(); + let parent = output.parent().unwrap(); + let leaf = output.file_name().unwrap().to_string_lossy(); + let orphan = parent.join(format!( + ".{}.dynwinrt-backup-orphan", + leaf.to_ascii_uppercase() + )); + fs::create_dir_all(&orphan).unwrap(); + fs::write(orphan.join("unrelated.txt"), "keep").unwrap(); + + let error = OutputTransaction::begin(&output) + .err() + .expect("orphaned nonce artifacts must fail closed"); + + assert!( + error.contains("Incomplete generated output transaction"), + "{error}" + ); + assert_eq!( + fs::read_to_string(orphan.join("unrelated.txt")).unwrap(), + "keep" + ); + fs::remove_dir_all(output).unwrap(); + fs::remove_dir_all(orphan).unwrap(); + } + + #[test] + fn output_transaction_excludes_concurrent_generation() { + let output = test_directory("transaction-lock"); + fs::create_dir_all(&output).unwrap(); + let first = OutputTransaction::begin(&output).unwrap(); + + let error = OutputTransaction::begin(&output) + .err() + .expect("a second transaction must not share the output"); + + assert!( + error.contains("Another generation is already using"), + "{error}" + ); + drop(first); + let next = OutputTransaction::begin(&output) + .expect("the lock must be released when the transaction drops"); + drop(next); + fs::remove_dir_all(output).unwrap(); + } + + #[cfg(windows)] + #[test] + fn output_transaction_rejects_linked_root_and_cleans_failed_stage() { + use std::os::windows::fs::{symlink_dir, symlink_file}; + + let output = test_directory("transaction-linked-root"); + let target = test_directory("transaction-linked-root-target"); + fs::create_dir_all(&target).unwrap(); + if let Err(error) = symlink_dir(&target, &output) { + eprintln!("Skipping transaction link test: {error}"); + fs::remove_dir_all(target).unwrap(); + return; + } + let error = OutputTransaction::begin(&output) + .err() + .expect("a linked transaction root must be rejected"); + assert!(error.contains("linked directory"), "{error}"); + fs::remove_dir(&output).unwrap(); + + fs::create_dir_all(&output).unwrap(); + let external = target.join("external.js"); + fs::write(&external, "outside").unwrap(); + symlink_file(&external, output.join("linked.js")).unwrap(); + let error = OutputTransaction::begin(&output) + .err() + .expect("a linked child must fail staging"); + assert!(error.contains("linked filesystem entry"), "{error}"); + let parent = output.parent().unwrap(); + let leaf = output.file_name().unwrap().to_string_lossy(); + assert!( + fs::read_dir(parent).unwrap().flatten().all(|entry| { + !entry + .file_name() + .to_string_lossy() + .starts_with(&format!(".{leaf}.dynwinrt-stage-")) + }), + "failed begin must not leak a staging directory" + ); + + fs::remove_file(output.join("linked.js")).unwrap(); + fs::remove_dir_all(output).unwrap(); + fs::remove_dir_all(target).unwrap(); + } + #[test] fn python_generation_emits_shared_runtime_and_typing_support() { let output = test_directory("python-shared-support"); @@ -4048,13 +6430,13 @@ mod tests { } #[test] - fn dropped_python_output_transaction_preserves_existing_output() { + fn dropped_output_transaction_preserves_existing_output() { let output = test_directory("transaction-drop"); fs::create_dir_all(&output).unwrap(); fs::write(output.join("existing.py"), "old").unwrap(); { - let transaction = PythonOutputTransaction::begin(&output).unwrap(); + let transaction = OutputTransaction::begin(&output).unwrap(); fs::write(transaction.stage_dir().join("existing.py"), "new").unwrap(); } diff --git a/tools/dynwinrt-codegen/src/meta.rs b/tools/dynwinrt-codegen/src/meta.rs index b62139f2..f6db045e 100644 --- a/tools/dynwinrt-codegen/src/meta.rs +++ b/tools/dynwinrt-codegen/src/meta.rs @@ -378,6 +378,7 @@ pub fn resolve_dependencies( existing_interfaces, existing_enums, false, + true, ) } @@ -394,6 +395,7 @@ pub fn resolve_python_dependencies( existing_interfaces, existing_enums, true, + false, ) } @@ -403,6 +405,7 @@ fn resolve_dependencies_impl( existing_interfaces: &[InterfaceMeta], existing_enums: &[TypeMeta], include_inheritance: bool, + fully_qualified_identity: bool, ) -> ResolvedDeps { let index = match load_index(winmd_paths) { Some(idx) => idx, @@ -428,6 +431,48 @@ fn resolve_dependencies_impl( known.insert(name.clone()); } } + let mut known_named = HashSet::new(); + known_named.extend(classes.iter().map(|class| TypeRef { + namespace: class.namespace.clone(), + name: class.name.clone(), + kind: TypeKind::Class, + })); + known_named.extend(existing_interfaces.iter().map(|interface| TypeRef { + namespace: interface.namespace.clone(), + name: interface.name.clone(), + kind: TypeKind::Interface, + })); + known_named.extend(existing_enums.iter().filter_map(|typ| { + let TypeMeta::Enum { + namespace, name, .. + } = typ + else { + return None; + }; + Some(TypeRef { + namespace: namespace.clone(), + name: name.clone(), + kind: TypeKind::Enum, + }) + })); + let mut known_parameterized = existing_interfaces + .iter() + .filter_map(|interface| { + interface.generic_piid.as_ref().map(|piid| { + let suffix = make_parameterized_name("", &interface.generic_args); + let generic_name = interface + .name + .strip_suffix(&suffix) + .unwrap_or(&interface.name); + parameterized_dependency_key( + &interface.namespace, + generic_name, + piid, + &interface.generic_args, + ) + }) + }) + .collect::>(); let mut dep_classes: Vec = Vec::new(); let mut dep_interfaces: Vec = Vec::new(); @@ -464,7 +509,11 @@ fn resolve_dependencies_impl( let mut new_interfaces = Vec::new(); for r in &batch { - if known.contains(&r.name) { + if fully_qualified_identity { + if !known_named.insert(r.clone()) { + continue; + } + } else if known.contains(&r.name) { continue; } known.insert(r.name.clone()); @@ -515,8 +564,30 @@ fn resolve_dependencies_impl( args, } = param_type { - let concrete_name = make_parameterized_name(name, args); - if known.contains(&concrete_name) { + let resolved_args = args + .iter() + .map(|argument| { + map_winmd_type_with_generics( + &type_meta_to_winmd_type(argument), + &index, + &[], + ) + }) + .collect::>(); + if resolved_args + .iter() + .any(|argument| !is_resolved_generic_arg(argument)) + { + continue; + } + let concrete_name = make_parameterized_name(name, &resolved_args); + if fully_qualified_identity { + let identity = + parameterized_dependency_key(namespace, name, piid, &resolved_args); + if !known_parameterized.insert(identity) { + continue; + } + } else if known.contains(&concrete_name) { continue; } known.insert(concrete_name.clone()); @@ -527,7 +598,7 @@ fn resolve_dependencies_impl( name, &concrete_name, piid, - args, + &resolved_args, ) { new_interfaces.push(iface); } else { @@ -624,7 +695,7 @@ fn visit_type_refs(typ: &TypeMeta, named: &mut Vec, parameterized: &mut /// Collect all type references from methods: both named and parameterized. fn collect_all_refs_from_methods( methods: &[MethodMeta], - known: &HashSet, + _known: &HashSet, named_out: &mut Vec, param_out: &mut Vec, ) { @@ -638,42 +709,90 @@ fn collect_all_refs_from_methods( visit_type_refs(rt, &mut named, &mut parameterized); } } - for r in named { - if !known.contains(&r.name) { - named_out.push(r); - } - } - for r in parameterized { - if let TypeMeta::Parameterized { name, args, .. } = &r { - let concrete = make_parameterized_name(name, args); - if !known.contains(&concrete) { - param_out.push(r); - } - } - } + named_out.extend(named); + param_out.extend(parameterized); } fn collect_interface_base_ref( base: &TypeMeta, - known: &HashSet, + _known: &HashSet, named_out: &mut Vec, param_out: &mut Vec, ) { let mut named = Vec::new(); let mut parameterized = Vec::new(); visit_type_refs(base, &mut named, &mut parameterized); - named_out.extend( - named - .into_iter() - .filter(|reference| !known.contains(&reference.name)), - ); - param_out.extend(parameterized.into_iter().filter(|reference| { - matches!( - reference, - TypeMeta::Parameterized { name, args, .. } - if !known.contains(&make_parameterized_name(name, args)) - ) - })); + named_out.extend(named); + param_out.extend(parameterized); +} + +fn type_dependency_key(typ: &TypeMeta) -> String { + match typ { + TypeMeta::Bool => "bool".into(), + TypeMeta::I8 => "i8".into(), + TypeMeta::U8 => "u8".into(), + TypeMeta::I16 => "i16".into(), + TypeMeta::U16 => "u16".into(), + TypeMeta::I32 => "i32".into(), + TypeMeta::U32 => "u32".into(), + TypeMeta::I64 => "i64".into(), + TypeMeta::U64 => "u64".into(), + TypeMeta::F32 => "f32".into(), + TypeMeta::F64 => "f64".into(), + TypeMeta::Char16 => "char16".into(), + TypeMeta::String => "string".into(), + TypeMeta::Guid => "guid".into(), + TypeMeta::Object => "object".into(), + TypeMeta::Interface { + namespace, name, .. + } => format!("interface:{namespace}.{name}"), + TypeMeta::RuntimeClass { + namespace, name, .. + } => format!("class:{namespace}.{name}"), + TypeMeta::Delegate { + namespace, name, .. + } => format!("delegate:{namespace}.{name}"), + TypeMeta::Parameterized { + namespace, + name, + piid, + args, + } => parameterized_dependency_key(namespace, name, piid, args), + TypeMeta::Array(inner) => format!("array:{}", type_dependency_key(inner)), + TypeMeta::Struct { + namespace, name, .. + } => format!("struct:{namespace}.{name}"), + TypeMeta::Enum { + namespace, name, .. + } => format!("enum:{namespace}.{name}"), + TypeMeta::AsyncAction => "async-action".into(), + TypeMeta::AsyncActionWithProgress(progress) => { + format!("async-action-progress:{}", type_dependency_key(progress)) + } + TypeMeta::AsyncOperation(result) => { + format!("async-operation:{}", type_dependency_key(result)) + } + TypeMeta::AsyncOperationWithProgress(result, progress) => format!( + "async-operation-progress:{},{}", + type_dependency_key(result), + type_dependency_key(progress) + ), + } +} + +fn parameterized_dependency_key( + namespace: &str, + name: &str, + piid: &str, + args: &[TypeMeta], +) -> String { + format!( + "generic:{namespace}.{name}:{piid}<{}>", + args.iter() + .map(type_dependency_key) + .collect::>() + .join(",") + ) } /// Generate a concrete name for a parameterized interface, e.g. "IVector_String", "IMap_String_Object". @@ -718,10 +837,7 @@ fn collect_all_refs_from_classes( include_class_bases: bool, ) { for c in classes { - if include_class_bases - && let Some(base) = &c.base_class - && !known.contains(&base.name) - { + if include_class_bases && let Some(base) = &c.base_class { named_out.push(base.clone()); } for iface in c.all_interfaces() { @@ -729,10 +845,7 @@ fn collect_all_refs_from_classes( } // Required interfaces themselves may need to be resolved for iface in &c.required_interfaces { - if iface.generic_piid.is_none() - && !iface.name.is_empty() - && !known.contains(&iface.name) - { + if iface.generic_piid.is_none() && !iface.name.is_empty() { named_out.push(TypeRef { namespace: iface.namespace.clone(), name: iface.name.clone(), @@ -765,10 +878,7 @@ fn collect_all_refs_from_interfaces( piid: PIID_IVECTOR.into(), args: i.generic_args.clone(), }; - let concrete_name = make_parameterized_name("IVector", &i.generic_args); - if !known.contains(&concrete_name) { - param_out.push(vector); - } + param_out.push(vector); } } } @@ -807,20 +917,29 @@ pub fn expand_winmd_paths(winmd_paths: &str) -> String { continue; } if let Ok(entries) = std::fs::read_dir(parent) { - for entry in entries.flatten() { - let path = entry.path(); - if path - .extension() - .map_or(false, |ext| ext.eq_ignore_ascii_case("winmd")) - { - let canonical = path - .canonicalize() - .map(|c| c.to_string_lossy().to_string()) - .unwrap_or_else(|_| path.to_string_lossy().to_string()); - if seen.insert(canonical) { - eprintln!("Auto-discovered sibling winmd: {}", path.display()); - all_paths.push(path.to_string_lossy().to_string()); - } + let mut siblings = entries + .flatten() + .map(|entry| entry.path()) + .filter(|path| { + path.extension() + .map_or(false, |ext| ext.eq_ignore_ascii_case("winmd")) + }) + .collect::>(); + siblings.sort_by(|left, right| { + let left = left.to_string_lossy(); + let right = right.to_string_lossy(); + left.to_ascii_lowercase() + .cmp(&right.to_ascii_lowercase()) + .then_with(|| left.cmp(&right)) + }); + for path in siblings { + let canonical = path + .canonicalize() + .map(|c| c.to_string_lossy().to_string()) + .unwrap_or_else(|_| path.to_string_lossy().to_string()); + if seen.insert(canonical) { + eprintln!("Auto-discovered sibling winmd: {}", path.display()); + all_paths.push(path.to_string_lossy().to_string()); } } } @@ -1854,6 +1973,24 @@ mod tests { assert_eq!(interfaces.len(), 2); } + #[test] + fn parameterized_dependency_identity_includes_argument_namespace() { + let key = |namespace: &str| { + parameterized_dependency_key( + WINDOWS_FOUNDATION_COLLECTIONS_NAMESPACE, + "IVector", + PIID_IVECTOR, + &[TypeMeta::RuntimeClass { + namespace: namespace.into(), + name: "PointerPoint".into(), + default_interface: None, + }], + ) + }; + + assert_ne!(key("Windows.UI.Input"), key("Microsoft.UI.Input")); + } + #[test] fn class_all_interfaces_iterates_all() { let mk_iface = |n: &str| InterfaceMeta { diff --git a/tools/dynwinrt-codegen/tests/composable_factory_test.rs b/tools/dynwinrt-codegen/tests/composable_factory_test.rs index 69249d14..09879162 100644 --- a/tools/dynwinrt-codegen/tests/composable_factory_test.rs +++ b/tools/dynwinrt-codegen/tests/composable_factory_test.rs @@ -3,7 +3,7 @@ use std::collections::{HashMap, HashSet}; -use dynwinrt_codegen::codegen::{project, python, python_stub, render_dts, render_js}; +use dynwinrt_codegen::codegen::{javascript, project, python, python_stub, render_dts, render_js}; use dynwinrt_codegen::meta::{ ClassMeta, ConstructorKind, ConstructorMeta, InterfaceMeta, MethodMeta, ParamDirection, ParamMeta, @@ -332,6 +332,12 @@ fn parameterized_default_interface_uses_computed_iid() { iid: "fe870f2f-89ef-5dac-9f33-968d0dc577c3".into(), })), }; + let vector_view_name = javascript::parameterized_name( + "Windows.Foundation.Collections", + "IVectorView", + "bbe1fa4c-b0e3-4583-baef-1f1b2e483e56", + std::slice::from_ref(&row_type), + ); let class = ClassMeta { name: "RowDefinitionCollection".into(), namespace: "Microsoft.UI.Xaml.Controls".into(), @@ -426,7 +432,7 @@ fn parameterized_default_interface_uses_computed_iid() { &HashSet::from([ "RowDefinition".into(), "RowDefinitionCollection".into(), - "IVectorView_RowDefinition".into(), + vector_view_name.clone(), ]), &HashSet::new(), &HashSet::new(), @@ -442,7 +448,7 @@ fn parameterized_default_interface_uses_computed_iid() { assert!(js.contains(&format!("const IID_RowDefinitionCollection = {expected};"))); assert!(js.contains("exports.IID_RowDefinitionCollection = IID_RowDefinitionCollection;")); assert!(!js.contains("require('./IVector_RowDefinition.js')")); - assert!(js.contains("require('./IVectorView_RowDefinition.js')")); + assert!(js.contains(&format!("require('./{vector_view_name}.js')"))); assert!(js.contains("_IVector_RowDefinition.method(9).invokeAll(this._obj")); assert!(dts.contains("indexOf(value: RowDefinition): number;")); assert!(dts.contains("append(value: RowDefinition): void;")); diff --git a/tools/dynwinrt-codegen/tests/ireference_struct_field_test.rs b/tools/dynwinrt-codegen/tests/ireference_struct_field_test.rs index c613662e..9c85dd1c 100644 --- a/tools/dynwinrt-codegen/tests/ireference_struct_field_test.rs +++ b/tools/dynwinrt-codegen/tests/ireference_struct_field_test.rs @@ -3,7 +3,7 @@ use std::collections::{HashMap, HashSet}; -use dynwinrt_codegen::codegen::winrt::javascript::project; +use dynwinrt_codegen::codegen::winrt::javascript::{self, project}; use dynwinrt_codegen::codegen::winrt::python; use dynwinrt_codegen::codegen::{python_stub, render_dts, render_js}; use dynwinrt_codegen::meta::{ @@ -112,6 +112,12 @@ fn generate_javascript(class: &ClassMeta, known: &HashSet) -> (String, S #[test] fn synthetic_ireference_point_field_uses_native_optional_projection() { let class = synthetic_class(); + let js_reference_name = javascript::parameterized_name( + "Windows.Foundation", + "IReference", + PIID_IREFERENCE, + std::slice::from_ref(&point()), + ); let known = HashSet::from([ "UsesOptionalPoint".to_string(), "Point".to_string(), @@ -148,7 +154,7 @@ fn synthetic_ireference_point_field_uses_native_optional_projection() { assert!(!pyi.contains("value(self) -> DynWinRTValue")); assert!( - dts.contains("value: Point | null | IReference_Point;"), + dts.contains(&format!("value: Point | null | {js_reference_name};")), "{dts}" ); assert!( @@ -166,7 +172,9 @@ fn synthetic_ireference_point_field_uses_native_optional_projection() { "{js}" ); assert!( - dts.contains("import { IReference_Point } from './IReference_Point.js';"), + dts.contains(&format!( + "import {{ {js_reference_name} }} from './{js_reference_name}.js';" + )), "{dts}" ); @@ -198,6 +206,12 @@ fn scalar_ireference_fields_preserve_native_python_types() { doc: None, deprecated: None, }; + let js_mode_reference_name = javascript::parameterized_name( + "Windows.Foundation", + "IReference", + PIID_IREFERENCE, + std::slice::from_ref(&mode), + ); let holder = TypeMeta::Struct { namespace: "Synthetic".into(), name: "OptionalScalars".into(), @@ -243,7 +257,7 @@ fn scalar_ireference_fields_preserve_native_python_types() { assert!( dts.contains("count: number | null | IReference_UInt32;") && dts.contains("label: string | null | IReference_String;") - && dts.contains("mode: Mode | null | IReference_Mode;"), + && dts.contains(&format!("mode: Mode | null | {js_mode_reference_name};")), "{dts}" ); assert!(js.contains("DynWinRtValue.u32(value)"), "{js}"); diff --git a/tools/dynwinrt-codegen/tests/javascript_dts_regression_test.rs b/tools/dynwinrt-codegen/tests/javascript_dts_regression_test.rs new file mode 100644 index 00000000..fb2e5713 --- /dev/null +++ b/tools/dynwinrt-codegen/tests/javascript_dts_regression_test.rs @@ -0,0 +1,175 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +use std::collections::{HashMap, HashSet}; + +use dynwinrt_codegen::codegen::{project, render_dts}; +use dynwinrt_codegen::meta::{ClassMeta, InterfaceMeta, MethodMeta, ParamDirection, ParamMeta}; +use dynwinrt_codegen::types::TypeMeta; + +#[test] +fn delegate_callback_return_imports_dynwinrt_value() { + let delegate = InterfaceMeta { + name: "CreateDefaultValueCallback".into(), + iid: "11111111-1111-1111-1111-111111111111".into(), + methods: vec![ + MethodMeta { + name: ".ctor".into(), + ..Default::default() + }, + MethodMeta { + name: "Invoke".into(), + return_type: Some(TypeMeta::Object), + ..Default::default() + }, + ], + ..Default::default() + }; + let delegate_names = HashSet::from([delegate.name.clone()]); + let (signatures, references, _) = project::build_delegate_signatures( + std::slice::from_ref(&delegate), + &delegate_names, + &delegate_names, + ); + + let projected = project::project_delegate(&delegate, &signatures, &references); + let dts = render_dts::render(&projected); + + assert!( + dts.contains("import { DynWinRtType, WinGuid, DynWinRtValue } from '@microsoft/dynwinrt';"), + "{dts}" + ); + assert!( + dts.contains("export type CreateDefaultValueCallback = () => DynWinRtValue;"), + "{dts}" + ); +} + +#[test] +fn imported_collection_interface_is_not_redeclared_inline() { + let map_type = TypeMeta::Parameterized { + namespace: "Windows.Foundation.Collections".into(), + name: "IMap".into(), + piid: "3c2925fe-8519-45c1-aa79-197b6718c1c1".into(), + args: vec![TypeMeta::Object, TypeMeta::Object], + }; + let map_interface = InterfaceMeta { + name: "IMap_Object_Object".into(), + iid: "22222222-2222-2222-2222-222222222222".into(), + generic_piid: Some("3c2925fe-8519-45c1-aa79-197b6718c1c1".into()), + generic_args: vec![TypeMeta::Object, TypeMeta::Object], + ..Default::default() + }; + let class = ClassMeta { + name: "ResourceDictionary".into(), + namespace: "Contoso".into(), + full_name: "Contoso.ResourceDictionary".into(), + default_interface: Some(InterfaceMeta { + name: "IResourceDictionary".into(), + iid: "33333333-3333-3333-3333-333333333333".into(), + methods: vec![MethodMeta { + name: "get_ThemeDictionaries".into(), + return_type: Some(map_type), + is_property_getter: true, + ..Default::default() + }], + ..Default::default() + }), + required_interfaces: vec![map_interface], + ..Default::default() + }; + let known_types = HashSet::from(["ResourceDictionary".into(), "IMap_Object_Object".into()]); + + let projected = project::project_class( + &class, + &known_types, + &HashSet::new(), + &HashSet::new(), + &HashMap::new(), + &HashMap::new(), + &HashMap::new(), + ); + let dts = render_dts::render(&projected); + + assert_eq!( + dts.matches("import { IMap_Object_Object } from './IMap_Object_Object.js';") + .count(), + 1, + "{dts}" + ); + assert!( + !dts.contains("export declare class IMap_Object_Object"), + "{dts}" + ); +} + +#[test] +fn imported_required_interface_contributes_method_overloads() { + let rewrite = |with_tone: bool| { + let mut params = vec![ParamMeta { + name: "text".into(), + typ: TypeMeta::String, + direction: ParamDirection::In, + }]; + if with_tone { + params.push(ParamMeta { + name: "tone".into(), + typ: TypeMeta::Enum { + namespace: "Contoso".into(), + name: "Tone".into(), + underlying: Box::new(TypeMeta::I32), + members: Vec::new(), + is_flags: false, + doc: None, + deprecated: None, + }, + direction: ParamDirection::In, + }); + } + MethodMeta { + name: "RewriteAsync".into(), + raw_name: "RewriteAsync".into(), + params, + return_type: Some(TypeMeta::AsyncOperation(Box::new(TypeMeta::String))), + ..Default::default() + } + }; + let versioned_iid = "22222222-2222-2222-2222-222222222222"; + let class = ClassMeta { + name: "Rewriter".into(), + namespace: "Contoso".into(), + full_name: "Contoso.Rewriter".into(), + default_interface: Some(InterfaceMeta { + name: "IRewriter".into(), + iid: "11111111-1111-1111-1111-111111111111".into(), + methods: vec![rewrite(false)], + ..Default::default() + }), + required_interfaces: vec![InterfaceMeta { + name: "IRewriter2".into(), + iid: versioned_iid.into(), + methods: vec![rewrite(true)], + ..Default::default() + }], + ..Default::default() + }; + let projected = project::project_class( + &class, + &HashSet::from(["Rewriter".into(), "IRewriter2".into(), "Tone".into()]), + &HashSet::new(), + &HashSet::from([versioned_iid.into()]), + &HashMap::new(), + &HashMap::new(), + &HashMap::new(), + ); + let dts = render_dts::render(&projected); + + assert!( + dts.contains("rewriteAsync(text: string, signal?: AbortSignal)"), + "{dts}" + ); + assert!( + dts.contains("rewriteAsync(text: string, tone: Tone, signal?: AbortSignal)"), + "{dts}" + ); +} diff --git a/tools/dynwinrt-codegen/tests/observable_vector_test.rs b/tools/dynwinrt-codegen/tests/observable_vector_test.rs index 3094bbe8..da28f070 100644 --- a/tools/dynwinrt-codegen/tests/observable_vector_test.rs +++ b/tools/dynwinrt-codegen/tests/observable_vector_test.rs @@ -29,18 +29,13 @@ fn observable_vector_projects_mutable_create_helper() { let dts = render_dts::render(&projected); assert!(js.contains("DynWinRtValue.createVector")); - assert!( - js.contains("new ((__load_IVector_Object()).IVector_Object)(value)",), - "{js}", - ); + assert!(js.contains("new (__get_IVector_Object())(value)",), "{js}",); assert!(js.contains("onVectorChanged")); assert!( js.contains("asVector: { value: observable.asVector.bind(observable) }"), "{js}", ); - assert!(js.contains( - "asVector() {\n return new ((__load_IVector_Object()).IVector_Object)(this._obj);", - )); + assert!(js.contains("asVector() {\n return new (__get_IVector_Object())(this._obj);",)); assert!(dts.contains("asVector(): IVector_Object;")); assert!(dts.contains( "static create(items: unknown[]): IObservableVector_Object & IVector_Object;", diff --git a/tools/dynwinrt-codegen/tests/output_cleanliness_test.rs b/tools/dynwinrt-codegen/tests/output_cleanliness_test.rs index a6557fb2..92a944cb 100644 --- a/tools/dynwinrt-codegen/tests/output_cleanliness_test.rs +++ b/tools/dynwinrt-codegen/tests/output_cleanliness_test.rs @@ -1,9 +1,9 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -//! Regression test: the JS code generator must only write public artifacts -//! (`.js` + `.d.ts`) into the output directory. No hidden cache files -//! (e.g. `.index.ts`), no temp files, no raw `.ts` sources. +//! Regression test: the JS code generator writes public modules plus its +//! generated type-identity inventory. No transient cache files +//! (e.g. `.index.ts`), temp files, or raw `.ts` sources may leak. use std::fs; use std::path::Path; @@ -65,17 +65,28 @@ fn output_dir_contains_no_internal_cache_files() { ); assert!(tmp.join("lifetime.js").exists()); assert!(tmp.join("lifetime.d.ts").exists()); + assert!( + tmp.join("windows") + .join("foundation") + .join("Uri.js") + .exists() + ); + assert!(!tmp.join("Uri.js").exists()); let index = fs::read_to_string(tmp.join("index.d.ts")).expect("read index.d.ts"); + assert!(index.contains("export { Uri } from './windows/foundation/Uri.js';")); assert!(index.contains("createProjectedLifetimeScope")); assert!(index.contains("projectAs")); assert!(index.contains("releaseProjected")); + let package = fs::read_to_string(tmp.join("package.json")).expect("read package.json"); + assert!(!package.contains("\"./Uri\"")); + assert!(package.contains("\"./windows/foundation/Uri\"")); let mut violations: Vec = Vec::new(); for entry in fs::read_dir(&tmp).expect("read tmp dir") { let e = entry.expect("dir entry"); let name = e.file_name().to_string_lossy().to_string(); - // No dotfiles in the public output dir. - if name.starts_with('.') { + // Only the generated JavaScript type inventory is allowed. + if name.starts_with('.') && name != ".dynwinrt-js-types" { violations.push(format!("hidden file leaked: {}", name)); } // No raw .ts sources — only .d.ts ambient declarations are allowed. @@ -132,7 +143,41 @@ fn output_dir_clean_full_namespace_mode() { ); assert!(tmp.join("lifetime.js").exists()); assert!(tmp.join("lifetime.d.ts").exists()); + assert!( + tmp.join("windows") + .join("foundation") + .join("Uri.js") + .exists() + ); + let uri_js_path = tmp.join("windows/foundation/Uri.js"); + let uri_dts_path = tmp.join("windows/foundation/Uri.d.ts"); + let uri_js_before = fs::read(&uri_js_path).unwrap(); + let uri_dts_before = fs::read(&uri_dts_path).unwrap(); + let incremental = Command::new(exe) + .args([ + "generate", + "--namespace", + "Windows.Foundation", + "--class-name", + "Uri", + "--lang", + "js", + "--output", + ]) + .arg(&tmp) + .status() + .expect("spawn incremental Uri generation"); + assert!(incremental.success()); + assert_eq!(fs::read(&uri_js_path).unwrap(), uri_js_before); + assert_eq!(fs::read(&uri_dts_path).unwrap(), uri_dts_before); + assert!(!tmp.join("IIterable_IWwwFormUrlDecoderEntry.js").exists()); + let decoder = fs::read_to_string(tmp.join("windows/foundation/WwwFormUrlDecoder.js")).unwrap(); + assert!( + decoder.contains("exports.IIterable_WindowsFoundationIWwwFormUrlDecoderEntry"), + "{decoder}" + ); let index = fs::read_to_string(tmp.join("index.d.ts")).expect("read index.d.ts"); + assert!(index.contains("export { Uri } from './windows/foundation/Uri.js';")); assert!(index.contains("createProjectedLifetimeScope")); assert!(index.contains("projectAs")); assert!(index.contains("releaseProjected")); @@ -142,7 +187,7 @@ fn output_dir_clean_full_namespace_mode() { for entry in fs::read_dir(&tmp).expect("read tmp dir") { let e = entry.expect("dir entry"); let name = e.file_name().to_string_lossy().to_string(); - if name.starts_with('.') { + if name.starts_with('.') && name != ".dynwinrt-js-types" { violations.push(format!("hidden file leaked: {}", name)); } if name.ends_with(".ts") && !name.ends_with(".d.ts") { @@ -159,6 +204,117 @@ fn output_dir_clean_full_namespace_mode() { ); } +#[test] +fn generated_languages_reject_current_directory_output_before_writing() { + if !Path::new(WINDOWS_WINMD).exists() { + eprintln!("Skipping: Windows.winmd not found"); + return; + } + + let exe = env!("CARGO_BIN_EXE_dynwinrt-codegen"); + let output = std::env::temp_dir().join(format!( + "dynwinrt-codegen-current-dir-{}", + std::process::id() + )); + let _ = fs::remove_dir_all(&output); + fs::create_dir_all(&output).unwrap(); + fs::write( + output.join("application.js"), + "exports.UnrelatedApplicationValue = 1;\n", + ) + .unwrap(); + let status = Command::new(exe) + .current_dir(&output) + .args([ + "generate", + "--namespace", + "Windows.Foundation", + "--class-name", + "Uri", + "--lang", + "js", + "--output", + ".", + ]) + .status() + .expect("spawn dynwinrt-codegen with current-directory output"); + assert!(!status.success()); + assert!(!output.join("Uri.js").exists()); + assert!(!output.join("windows/foundation/Uri.js").exists()); + assert_eq!( + fs::read_to_string(output.join("application.js")).unwrap(), + "exports.UnrelatedApplicationValue = 1;\n" + ); + assert!(!output.join("package.json").exists()); + assert!(!output.join("index.js").exists()); + let python_status = Command::new(exe) + .current_dir(&output) + .args([ + "generate", + "--namespace", + "Windows.Foundation", + "--class-name", + "Uri", + "--lang", + "py", + "--output", + ".", + ]) + .status() + .expect("spawn Python codegen with current-directory output"); + assert!(!python_status.success()); + assert!(!output.join("__init__.py").exists()); + assert!(!output.join("pyproject.toml").exists()); + fs::remove_dir_all(output).unwrap(); +} + +#[test] +fn public_winrt_interface_request_keeps_interface_members_and_struct_helpers() { + if !Path::new(WINDOWS_WINMD).exists() { + eprintln!("Skipping: Windows.winmd not found"); + return; + } + + let exe = env!("CARGO_BIN_EXE_dynwinrt-codegen"); + let output = std::env::temp_dir().join(format!( + "dynwinrt-codegen-public-interface-{}", + std::process::id() + )); + let _ = fs::remove_dir_all(&output); + let status = Command::new(exe) + .args([ + "generate", + "--namespace", + "Windows.Graphics.DirectX.Direct3D11", + "--class-name", + "IDirect3DSurface", + "--lang", + "js", + "--output", + ]) + .arg(&output) + .status() + .expect("spawn dynwinrt-codegen for public WinRT interface"); + assert!(status.success()); + + let canonical = fs::read_to_string( + output + .join("windows") + .join("graphics") + .join("direct-x") + .join("direct3-d11") + .join("IDirect3DSurface.js"), + ) + .expect("read canonical IDirect3DSurface"); + assert!(canonical.contains("get description()"), "{canonical}"); + assert!( + canonical.contains("packDirect3DSurfaceDescription"), + "{canonical}" + ); + assert!(!output.join("IDirect3DSurface.js").exists()); + fs::remove_dir_all(output).unwrap(); +} + #[test] fn python_emits_stubs_by_default_and_supports_opt_out() { if !Path::new(WINDOWS_WINMD).exists() { diff --git a/tools/dynwinrt-codegen/tests/snapshot_test.rs b/tools/dynwinrt-codegen/tests/snapshot_test.rs index eb3aa43f..b01ebcbb 100644 --- a/tools/dynwinrt-codegen/tests/snapshot_test.rs +++ b/tools/dynwinrt-codegen/tests/snapshot_test.rs @@ -13,7 +13,7 @@ use std::path::Path; use dynwinrt_codegen::codegen::common::to_snake_case_filename; use dynwinrt_codegen::codegen::python_stub; -use dynwinrt_codegen::codegen::{project, render_dts, render_js}; +use dynwinrt_codegen::codegen::{javascript, project, render_dts, render_js}; use dynwinrt_codegen::meta; use dynwinrt_codegen::types::TypeMeta; @@ -35,8 +35,67 @@ fn snapshot_uri_class() { let deps = meta::resolve_dependencies(winmd, &classes, &[], &[]); let mut all_classes = classes; all_classes.extend(deps.classes); - let all_interfaces = deps.interfaces; - let all_enums = deps.enums; + let mut all_interfaces = deps.interfaces; + let mut all_enums = deps.enums; + let identities = all_classes + .iter() + .map(|class| { + javascript::JavaScriptTypeIdentity::new( + &class.namespace, + &class.name, + javascript::JavaScriptTypeKind::Class, + ) + }) + .chain(all_interfaces.iter().map(|interface| { + let kind = if interface + .methods + .iter() + .any(|method| method.name == ".ctor") + && interface + .methods + .iter() + .any(|method| method.name == "Invoke") + { + javascript::JavaScriptTypeKind::Delegate + } else { + javascript::JavaScriptTypeKind::Interface + }; + if let Some(piid) = &interface.generic_piid { + javascript::JavaScriptTypeIdentity::with_variant( + &interface.namespace, + &javascript::parameterized_interface_name( + &interface.namespace, + &interface.name, + piid, + &interface.generic_args, + ), + kind, + &javascript::parameterized_reference_identity(piid, &interface.generic_args), + ) + } else { + javascript::JavaScriptTypeIdentity::new(&interface.namespace, &interface.name, kind) + } + })) + .chain(all_enums.iter().filter_map(|typ| { + let TypeMeta::Enum { + namespace, name, .. + } = typ + else { + return None; + }; + Some(javascript::JavaScriptTypeIdentity::new( + namespace, + name, + javascript::JavaScriptTypeKind::Enum, + )) + })) + .collect::>(); + let _layout = javascript::install_javascript_module_layout(identities).unwrap(); + javascript::apply_javascript_projected_names( + &mut all_classes, + &mut all_interfaces, + &mut all_enums, + ); let mut known_types: HashSet = HashSet::new(); for c in &all_classes { @@ -60,14 +119,18 @@ fn snapshot_uri_class() { .map(|i| i.name.clone()) .collect(); - let shared_iids: HashSet = HashSet::new(); + let shared_iids = all_interfaces + .iter() + .filter(|interface| interface.generic_piid.is_none()) + .map(|interface| interface.iid.clone()) + .collect::>(); let (delegate_sigs, delegate_sig_refs, delegate_param_wraps) = project::build_delegate_signatures(&all_interfaces, &delegate_type_names, &known_types); // Generate all files into a map (.js + .d.ts pair per type) let mut generated: HashMap = HashMap::new(); for iface in &all_interfaces { - let projected = project::project_interface( + let mut projected = project::project_interface( iface, &known_types, &delegate_type_names, @@ -75,13 +138,19 @@ fn snapshot_uri_class() { &delegate_sig_refs, &delegate_param_wraps, ); - let js = render_js::render(&projected); + let target = javascript::configure_projected_file(&mut projected).unwrap(); + let mut js = render_js::render(&projected); + let lifetime = javascript::root_relative_module(&target.canonical_module, "lifetime"); + js = js.replace( + "require('./lifetime.js')", + &format!("require('{lifetime}.js')"), + ); let dts = render_dts::render(&projected); - generated.insert(format!("{}.js", iface.name), js); - generated.insert(format!("{}.d.ts", iface.name), dts); + generated.insert(format!("{}.js", target.canonical_module), js); + generated.insert(format!("{}.d.ts", target.canonical_module), dts); } for class in &all_classes { - let projected = project::project_class( + let mut projected = project::project_class( class, &known_types, &delegate_type_names, @@ -90,12 +159,20 @@ fn snapshot_uri_class() { &delegate_sig_refs, &delegate_param_wraps, ); - let js = render_js::render(&projected); + let target = javascript::configure_projected_file(&mut projected).unwrap(); + let mut js = render_js::render(&projected); + let lifetime = javascript::root_relative_module(&target.canonical_module, "lifetime"); + js = js.replace( + "require('./lifetime.js')", + &format!("require('{lifetime}.js')"), + ); let dts = render_dts::render(&projected); - generated.insert(format!("{}.js", class.name), js); - generated.insert(format!("{}.d.ts", class.name), dts); + generated.insert(format!("{}.js", target.canonical_module), js); + generated.insert(format!("{}.d.ts", target.canonical_module), dts); } - let uri_js = generated.get("Uri.js").expect("generated Uri.js"); + let uri_js = generated + .get("windows/foundation/Uri.js") + .expect("generated Uri.js"); assert!(uri_js.contains( "const IID_ARG_Windows_Foundation_Uri = WinGuid.parse('9e365e57-48b2-4160-956f-c7385120bbfc');" )); @@ -111,6 +188,14 @@ fn snapshot_uri_class() { "Snapshot directory not found: {}", snapshot_dir.display() ); + if std::env::var_os("DYNWINRT_UPDATE_SNAPSHOTS").is_some() { + for (filename, actual) in &generated { + let path = snapshot_dir.join(filename); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, actual) + .unwrap_or_else(|error| panic!("Failed to update {filename}: {error}")); + } + } let mut mismatches = Vec::new(); for (filename, actual) in &generated { @@ -127,16 +212,31 @@ fn snapshot_uri_class() { } } - // Check for extra snapshot files not in generated output - if let Ok(entries) = fs::read_dir(&snapshot_dir) { - for entry in entries.flatten() { - let name = entry.file_name().to_string_lossy().to_string(); - if (name.ends_with(".js") || name.ends_with(".d.ts")) && !generated.contains_key(&name) + // Check for extra snapshot files not in generated output. + let mut snapshot_files = Vec::new(); + let mut directories = vec![snapshot_dir.clone()]; + while let Some(directory) = directories.pop() { + for entry in fs::read_dir(directory).unwrap().flatten() { + let path = entry.path(); + if path.is_dir() { + directories.push(path); + } else if path.extension().is_some_and(|extension| extension == "js") + || path.to_string_lossy().ends_with(".d.ts") { - mismatches.push(format!(" extra snapshot not generated: {}", name)); + snapshot_files.push(path); } } } + for path in snapshot_files { + let relative = path + .strip_prefix(&snapshot_dir) + .unwrap() + .to_string_lossy() + .replace('\\', "/"); + if !generated.contains_key(&relative) { + mismatches.push(format!(" extra snapshot not generated: {relative}")); + } + } if !mismatches.is_empty() { panic!( diff --git a/tools/dynwinrt-codegen/tests/snapshots/uri/IIterator_IWwwFormUrlDecoderEntry.js b/tools/dynwinrt-codegen/tests/snapshots/uri/IIterator_IWwwFormUrlDecoderEntry.js deleted file mode 100644 index 881c67a3..00000000 --- a/tools/dynwinrt-codegen/tests/snapshots/uri/IIterator_IWwwFormUrlDecoderEntry.js +++ /dev/null @@ -1,64 +0,0 @@ -// Generated by dynwinrt-codegen — do not edit -const { DynWinRtType, DynWinRtMethodSig, DynWinRtValue, DynWinRtArray, DynWinRtDelegate, WinGuid } = require('@microsoft/dynwinrt'); -require('./IWwwFormUrlDecoderEntry.js'); -let __m_IWwwFormUrlDecoderEntry; -const __load_IWwwFormUrlDecoderEntry = () => (__m_IWwwFormUrlDecoderEntry ??= require('./IWwwFormUrlDecoderEntry.js')); -const __get_IWwwFormUrlDecoderEntry = () => __load_IWwwFormUrlDecoderEntry().IWwwFormUrlDecoderEntry; - -const _unwrap = (x) => x?._obj ?? x; - -const IID_IIterator_IWwwFormUrlDecoderEntry = DynWinRtType.parameterized(WinGuid.parse('6a79e863-4300-459a-9966-cbb660963ee1'), [DynWinRtType.interface(WinGuid.parse('125e7431-f678-4e8e-b670-20a9b06c512d'))]).iid(); - -let _IIterator_IWwwFormUrlDecoderEntryCache; -const _IIterator_IWwwFormUrlDecoderEntry = new Proxy({}, { - get(_target, prop) { - _IIterator_IWwwFormUrlDecoderEntryCache ??= DynWinRtType.registerInterface( - "IIterator_IWwwFormUrlDecoderEntry", IID_IIterator_IWwwFormUrlDecoderEntry) - .addMethod("get_Current", new DynWinRtMethodSig().addOut(DynWinRtType.interface(WinGuid.parse('125e7431-f678-4e8e-b670-20a9b06c512d')))) - .addMethod("get_HasCurrent", new DynWinRtMethodSig().addOut(DynWinRtType.boolType())) - .addMethod("MoveNext", new DynWinRtMethodSig().addOut(DynWinRtType.boolType())) - .addMethod("GetMany", new DynWinRtMethodSig().addOutFill(DynWinRtType.arrayType(DynWinRtType.interface(WinGuid.parse('125e7431-f678-4e8e-b670-20a9b06c512d')))).addOut(DynWinRtType.u32())); - const value = _IIterator_IWwwFormUrlDecoderEntryCache[prop]; - return typeof value === 'function' ? value.bind(_IIterator_IWwwFormUrlDecoderEntryCache) : value; - } -}); - -class IIterator_IWwwFormUrlDecoderEntry { - _obj; - - constructor(obj) { - this._obj = obj.cast(IID_IIterator_IWwwFormUrlDecoderEntry); - } - - static from(obj) { - return new IIterator_IWwwFormUrlDecoderEntry(obj.cast(IID_IIterator_IWwwFormUrlDecoderEntry)); - } - - get current() { - return ((v) => v.isNull() ? null : new (__get_IWwwFormUrlDecoderEntry())(v))((() => { const _m = _IIterator_IWwwFormUrlDecoderEntry.method(6); return typeof _m.getObj === 'function' ? _m.getObj(this._obj) : _m.invoke(this._obj, []); })()); - } - - get hasCurrent() { - return (() => { const _m = _IIterator_IWwwFormUrlDecoderEntry.method(7); return typeof _m.getBool === 'function' ? _m.getBool(this._obj) : _IIterator_IWwwFormUrlDecoderEntry.method(7).invoke(this._obj, []).toBool(); })(); - } - - moveNext() { - return _IIterator_IWwwFormUrlDecoderEntry.method(8).invoke(this._obj, []).toBool(); - } - - getMany(items) { - return (() => { const _r = _IIterator_IWwwFormUrlDecoderEntry.method(9).invokeAll(this._obj, [(Array.isArray(items) ? DynWinRtArray.fromObjectValues(items.map(_i => _unwrap(_i)), DynWinRtType.interface(WinGuid.parse('125e7431-f678-4e8e-b670-20a9b06c512d'))).toValue() : _unwrap(items))]); return _r[0].asArray().toValues().map(v => v.isNull() ? null : new (__get_IWwwFormUrlDecoderEntry())(v)).slice(0, _r[1].toNumber()); })(); - } - - /** JS iterator protocol: returns the current element and advances. */ - next() { - if (!this.hasCurrent) return { value: undefined, done: true }; - const value = this.current; - this.moveNext(); - return { value, done: false }; - } - - [Symbol.iterator]() { return this; } -} -exports.IID_IIterator_IWwwFormUrlDecoderEntry = IID_IIterator_IWwwFormUrlDecoderEntry; -exports.IIterator_IWwwFormUrlDecoderEntry = IIterator_IWwwFormUrlDecoderEntry; diff --git a/tools/dynwinrt-codegen/tests/snapshots/uri/IStringable.d.ts b/tools/dynwinrt-codegen/tests/snapshots/uri/windows/foundation/IStringable.d.ts similarity index 100% rename from tools/dynwinrt-codegen/tests/snapshots/uri/IStringable.d.ts rename to tools/dynwinrt-codegen/tests/snapshots/uri/windows/foundation/IStringable.d.ts diff --git a/tools/dynwinrt-codegen/tests/snapshots/uri/IStringable.js b/tools/dynwinrt-codegen/tests/snapshots/uri/windows/foundation/IStringable.js similarity index 100% rename from tools/dynwinrt-codegen/tests/snapshots/uri/IStringable.js rename to tools/dynwinrt-codegen/tests/snapshots/uri/windows/foundation/IStringable.js diff --git a/tools/dynwinrt-codegen/tests/snapshots/uri/IUriRuntimeClassWithAbsoluteCanonicalUri.d.ts b/tools/dynwinrt-codegen/tests/snapshots/uri/windows/foundation/IUriRuntimeClassWithAbsoluteCanonicalUri.d.ts similarity index 100% rename from tools/dynwinrt-codegen/tests/snapshots/uri/IUriRuntimeClassWithAbsoluteCanonicalUri.d.ts rename to tools/dynwinrt-codegen/tests/snapshots/uri/windows/foundation/IUriRuntimeClassWithAbsoluteCanonicalUri.d.ts diff --git a/tools/dynwinrt-codegen/tests/snapshots/uri/IUriRuntimeClassWithAbsoluteCanonicalUri.js b/tools/dynwinrt-codegen/tests/snapshots/uri/windows/foundation/IUriRuntimeClassWithAbsoluteCanonicalUri.js similarity index 100% rename from tools/dynwinrt-codegen/tests/snapshots/uri/IUriRuntimeClassWithAbsoluteCanonicalUri.js rename to tools/dynwinrt-codegen/tests/snapshots/uri/windows/foundation/IUriRuntimeClassWithAbsoluteCanonicalUri.js diff --git a/tools/dynwinrt-codegen/tests/snapshots/uri/IWwwFormUrlDecoderEntry.d.ts b/tools/dynwinrt-codegen/tests/snapshots/uri/windows/foundation/IWwwFormUrlDecoderEntry.d.ts similarity index 100% rename from tools/dynwinrt-codegen/tests/snapshots/uri/IWwwFormUrlDecoderEntry.d.ts rename to tools/dynwinrt-codegen/tests/snapshots/uri/windows/foundation/IWwwFormUrlDecoderEntry.d.ts diff --git a/tools/dynwinrt-codegen/tests/snapshots/uri/IWwwFormUrlDecoderEntry.js b/tools/dynwinrt-codegen/tests/snapshots/uri/windows/foundation/IWwwFormUrlDecoderEntry.js similarity index 100% rename from tools/dynwinrt-codegen/tests/snapshots/uri/IWwwFormUrlDecoderEntry.js rename to tools/dynwinrt-codegen/tests/snapshots/uri/windows/foundation/IWwwFormUrlDecoderEntry.js diff --git a/tools/dynwinrt-codegen/tests/snapshots/uri/Uri.d.ts b/tools/dynwinrt-codegen/tests/snapshots/uri/windows/foundation/Uri.d.ts similarity index 72% rename from tools/dynwinrt-codegen/tests/snapshots/uri/Uri.d.ts rename to tools/dynwinrt-codegen/tests/snapshots/uri/windows/foundation/Uri.d.ts index 0dc87b99..c9dd61f2 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/uri/Uri.d.ts +++ b/tools/dynwinrt-codegen/tests/snapshots/uri/windows/foundation/Uri.d.ts @@ -37,23 +37,3 @@ export declare class Uri { get absoluteCanonicalUri(): string; get displayIri(): string; } - -export declare class IUriRuntimeClassWithAbsoluteCanonicalUri { - private constructor(); - - /** @internal Cast a raw WinRT object to this interface. */ - static from(obj: any): IUriRuntimeClassWithAbsoluteCanonicalUri; - - get absoluteCanonicalUri(): string; - - get displayIri(): string; -} - -export declare class IStringable { - private constructor(); - - /** @internal Cast a raw WinRT object to this interface. */ - static from(obj: any): IStringable; - - toString(): string; -} diff --git a/tools/dynwinrt-codegen/tests/snapshots/uri/Uri.js b/tools/dynwinrt-codegen/tests/snapshots/uri/windows/foundation/Uri.js similarity index 89% rename from tools/dynwinrt-codegen/tests/snapshots/uri/Uri.js rename to tools/dynwinrt-codegen/tests/snapshots/uri/windows/foundation/Uri.js index 5ce43d49..2245305f 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/uri/Uri.js +++ b/tools/dynwinrt-codegen/tests/snapshots/uri/windows/foundation/Uri.js @@ -3,8 +3,16 @@ const { DynWinRtType, DynWinRtMethodSig, DynWinRtValue, DynWinRtArray, DynWinRtD let __m_WwwFormUrlDecoder; const __load_WwwFormUrlDecoder = () => (__m_WwwFormUrlDecoder ??= require('./WwwFormUrlDecoder.js')); const __get_WwwFormUrlDecoder = () => __load_WwwFormUrlDecoder().WwwFormUrlDecoder; +const { IID_IUriRuntimeClassWithAbsoluteCanonicalUri } = require('./IUriRuntimeClassWithAbsoluteCanonicalUri.js'); +let __m_IUriRuntimeClassWithAbsoluteCanonicalUri; +const __load_IUriRuntimeClassWithAbsoluteCanonicalUri = () => (__m_IUriRuntimeClassWithAbsoluteCanonicalUri ??= require('./IUriRuntimeClassWithAbsoluteCanonicalUri.js')); +const __get_IUriRuntimeClassWithAbsoluteCanonicalUri = () => __load_IUriRuntimeClassWithAbsoluteCanonicalUri().IUriRuntimeClassWithAbsoluteCanonicalUri; +const { IID_IStringable } = require('./IStringable.js'); +let __m_IStringable; +const __load_IStringable = () => (__m_IStringable ??= require('./IStringable.js')); +const __get_IStringable = () => __load_IStringable().IStringable; let __m_lifetime; -const __load_lifetime = () => (__m_lifetime ??= require('./lifetime.js')); +const __load_lifetime = () => (__m_lifetime ??= require('../../lifetime.js')); const __get_castProjectedValueBorrowed = () => __load_lifetime().castProjectedValueBorrowed; const __get_castProjectedValueOwned = () => __load_lifetime().castProjectedValueOwned; const __get_trackProjectedValue = () => __load_lifetime().trackProjectedValue; @@ -14,8 +22,6 @@ const _unwrap = (x) => x?._obj ?? x; const IID_IUriRuntimeClass = WinGuid.parse('9e365e57-48b2-4160-956f-c7385120bbfc'); const IID_IUriRuntimeClassFactory = WinGuid.parse('44a9796f-723e-4fdf-a218-033e75b0c084'); const IID_IUriEscapeStatics = WinGuid.parse('c1d432ba-c824-4452-a7fd-512bc3bbe9a1'); -const IID_IUriRuntimeClassWithAbsoluteCanonicalUri = WinGuid.parse('758d9661-221c-480f-a339-50656673f46f'); -const IID_IStringable = WinGuid.parse('96369f54-8eb6-48f0-abce-c1b211e627c3'); const IID_Uri = WinGuid.parse('9e365e57-48b2-4160-956f-c7385120bbfc'); const IID_ARG_Windows_Foundation_Uri = WinGuid.parse('9e365e57-48b2-4160-956f-c7385120bbfc'); @@ -181,7 +187,7 @@ class Uri { return ((v) => v.isNull() ? null : Uri._fromNative(v))(_IUriRuntimeClass.method(22).invoke(this._obj, [DynWinRtValue.hstring(relativeUri)])); } toString() { - return IStringable.from(this._obj).toString(); + return (__get_IStringable()).from(this._obj).toString(); } [Symbol.toPrimitive](_hint) { return this.toString(); @@ -197,43 +203,5 @@ class Uri { return (() => { const _m = _IUriRuntimeClassWithAbsoluteCanonicalUri.method(7); return typeof _m.getString === 'function' ? _m.getString(this._obj.cast(IID_IUriRuntimeClassWithAbsoluteCanonicalUri)) : _IUriRuntimeClassWithAbsoluteCanonicalUri.method(7).invoke(this._obj.cast(IID_IUriRuntimeClassWithAbsoluteCanonicalUri), []).toString(); })(); } } - -class IUriRuntimeClassWithAbsoluteCanonicalUri { - _obj; - - constructor(obj) { - this._obj = obj; - } - - static from(obj) { - return new IUriRuntimeClassWithAbsoluteCanonicalUri(obj.cast(IID_IUriRuntimeClassWithAbsoluteCanonicalUri)); - } - - get absoluteCanonicalUri() { - return (() => { const _m = _IUriRuntimeClassWithAbsoluteCanonicalUri.method(6); return typeof _m.getString === 'function' ? _m.getString(this._obj) : _IUriRuntimeClassWithAbsoluteCanonicalUri.method(6).invoke(this._obj, []).toString(); })(); - } - - get displayIri() { - return (() => { const _m = _IUriRuntimeClassWithAbsoluteCanonicalUri.method(7); return typeof _m.getString === 'function' ? _m.getString(this._obj) : _IUriRuntimeClassWithAbsoluteCanonicalUri.method(7).invoke(this._obj, []).toString(); })(); - } -} - -class IStringable { - _obj; - - constructor(obj) { - this._obj = obj; - } - - static from(obj) { - return new IStringable(obj.cast(IID_IStringable)); - } - - toString() { - return _IStringable.method(6).invoke(this._obj, []).toString(); - } -} exports.IID_Uri = IID_Uri; exports.Uri = Uri; -exports.IUriRuntimeClassWithAbsoluteCanonicalUri = IUriRuntimeClassWithAbsoluteCanonicalUri; -exports.IStringable = IStringable; diff --git a/tools/dynwinrt-codegen/tests/snapshots/uri/WwwFormUrlDecoder.d.ts b/tools/dynwinrt-codegen/tests/snapshots/uri/windows/foundation/WwwFormUrlDecoder.d.ts similarity index 71% rename from tools/dynwinrt-codegen/tests/snapshots/uri/WwwFormUrlDecoder.d.ts rename to tools/dynwinrt-codegen/tests/snapshots/uri/windows/foundation/WwwFormUrlDecoder.d.ts index fa155bcc..dbc6827f 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/uri/WwwFormUrlDecoder.d.ts +++ b/tools/dynwinrt-codegen/tests/snapshots/uri/windows/foundation/WwwFormUrlDecoder.d.ts @@ -1,6 +1,6 @@ // Generated by dynwinrt-codegen — do not edit import { WinGuid } from '@microsoft/dynwinrt'; -import { IIterator_IWwwFormUrlDecoderEntry } from './IIterator_IWwwFormUrlDecoderEntry.js'; +import { IIterator_WindowsFoundationIWwwFormUrlDecoderEntry_g498f64075ebd0fce } from './collections/IIterator_WindowsFoundationIWwwFormUrlDecoderEntry_g498f64075ebd0fce.js'; import { IWwwFormUrlDecoderEntry } from './IWwwFormUrlDecoderEntry.js'; export declare const IID_WwwFormUrlDecoder: WinGuid; @@ -25,14 +25,14 @@ export declare class WwwFormUrlDecoder { * Return the index of `value`, or -1 if not found. */ indexOf(value: IWwwFormUrlDecoderEntry): number; - first(): IIterator_IWwwFormUrlDecoderEntry; + first(): IIterator_WindowsFoundationIWwwFormUrlDecoderEntry_g498f64075ebd0fce; } -export declare class IVectorView_IWwwFormUrlDecoderEntry { +export declare class IVectorView_WindowsFoundationIWwwFormUrlDecoderEntry_g58829236a97a8635 { private constructor(); /** @internal Cast a raw WinRT object to this interface. */ - static from(obj: any): IVectorView_IWwwFormUrlDecoderEntry; + static from(obj: any): IVectorView_WindowsFoundationIWwwFormUrlDecoderEntry_g58829236a97a8635; getAt(index: number): IWwwFormUrlDecoderEntry; @@ -58,13 +58,13 @@ export declare class IVectorView_IWwwFormUrlDecoderEntry { indexOf(value: IWwwFormUrlDecoderEntry): number; } -export declare class IIterable_IWwwFormUrlDecoderEntry { +export declare class IIterable_WindowsFoundationIWwwFormUrlDecoderEntry_gd13025e9604dbcdb { private constructor(); /** @internal Cast a raw WinRT object to this interface. */ - static from(obj: any): IIterable_IWwwFormUrlDecoderEntry; + static from(obj: any): IIterable_WindowsFoundationIWwwFormUrlDecoderEntry_gd13025e9604dbcdb; - first(): IIterator_IWwwFormUrlDecoderEntry; + first(): IIterator_WindowsFoundationIWwwFormUrlDecoderEntry_g498f64075ebd0fce; [Symbol.iterator](): IterableIterator; diff --git a/tools/dynwinrt-codegen/tests/snapshots/uri/WwwFormUrlDecoder.js b/tools/dynwinrt-codegen/tests/snapshots/uri/windows/foundation/WwwFormUrlDecoder.js similarity index 55% rename from tools/dynwinrt-codegen/tests/snapshots/uri/WwwFormUrlDecoder.js rename to tools/dynwinrt-codegen/tests/snapshots/uri/windows/foundation/WwwFormUrlDecoder.js index 6c5274fe..725946ba 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/uri/WwwFormUrlDecoder.js +++ b/tools/dynwinrt-codegen/tests/snapshots/uri/windows/foundation/WwwFormUrlDecoder.js @@ -1,14 +1,14 @@ // Generated by dynwinrt-codegen — do not edit const { DynWinRtType, DynWinRtMethodSig, DynWinRtValue, DynWinRtArray, DynWinRtDelegate, WinGuid } = require('@microsoft/dynwinrt'); -let __m_IIterator_IWwwFormUrlDecoderEntry; -const __load_IIterator_IWwwFormUrlDecoderEntry = () => (__m_IIterator_IWwwFormUrlDecoderEntry ??= require('./IIterator_IWwwFormUrlDecoderEntry.js')); -const __get_IIterator_IWwwFormUrlDecoderEntry = () => __load_IIterator_IWwwFormUrlDecoderEntry().IIterator_IWwwFormUrlDecoderEntry; +let __m_collections_IIterator_WindowsFoundationIWwwFormUrlDecoderEntry_g498f64075ebd0fce_50108df6; +const __load_collections_IIterator_WindowsFoundationIWwwFormUrlDecoderEntry_g498f64075ebd0fce_50108df6 = () => (__m_collections_IIterator_WindowsFoundationIWwwFormUrlDecoderEntry_g498f64075ebd0fce_50108df6 ??= require('./collections/IIterator_WindowsFoundationIWwwFormUrlDecoderEntry_g498f64075ebd0fce.js')); +const __get_IIterator_WindowsFoundationIWwwFormUrlDecoderEntry_g498f64075ebd0fce = () => __load_collections_IIterator_WindowsFoundationIWwwFormUrlDecoderEntry_g498f64075ebd0fce_50108df6().IIterator_WindowsFoundationIWwwFormUrlDecoderEntry_g498f64075ebd0fce; require('./IWwwFormUrlDecoderEntry.js'); let __m_IWwwFormUrlDecoderEntry; const __load_IWwwFormUrlDecoderEntry = () => (__m_IWwwFormUrlDecoderEntry ??= require('./IWwwFormUrlDecoderEntry.js')); const __get_IWwwFormUrlDecoderEntry = () => __load_IWwwFormUrlDecoderEntry().IWwwFormUrlDecoderEntry; let __m_lifetime; -const __load_lifetime = () => (__m_lifetime ??= require('./lifetime.js')); +const __load_lifetime = () => (__m_lifetime ??= require('../../lifetime.js')); const __get_castProjectedValueBorrowed = () => __load_lifetime().castProjectedValueBorrowed; const __get_castProjectedValueOwned = () => __load_lifetime().castProjectedValueOwned; const __get_trackProjectedValue = () => __load_lifetime().trackProjectedValue; @@ -17,8 +17,8 @@ const _unwrap = (x) => x?._obj ?? x; const IID_IWwwFormUrlDecoderRuntimeClass = WinGuid.parse('d45a0451-f225-4542-9296-0e1df5d254df'); const IID_IWwwFormUrlDecoderRuntimeClassFactory = WinGuid.parse('5b8c6b3d-24ae-41b5-a1bf-f0c3d544845b'); -const IID_IVectorView_IWwwFormUrlDecoderEntry = DynWinRtType.parameterized(WinGuid.parse('bbe1fa4c-b0e3-4583-baef-1f1b2e483e56'), [DynWinRtType.interface(WinGuid.parse('125e7431-f678-4e8e-b670-20a9b06c512d'))]).iid(); -const IID_IIterable_IWwwFormUrlDecoderEntry = DynWinRtType.parameterized(WinGuid.parse('faa585ea-6214-4217-afda-7f46de5869b3'), [DynWinRtType.interface(WinGuid.parse('125e7431-f678-4e8e-b670-20a9b06c512d'))]).iid(); +const IID_IVectorView_WindowsFoundationIWwwFormUrlDecoderEntry_g58829236a97a8635 = DynWinRtType.parameterized(WinGuid.parse('bbe1fa4c-b0e3-4583-baef-1f1b2e483e56'), [DynWinRtType.interface(WinGuid.parse('125e7431-f678-4e8e-b670-20a9b06c512d'))]).iid(); +const IID_IIterable_WindowsFoundationIWwwFormUrlDecoderEntry_gd13025e9604dbcdb = DynWinRtType.parameterized(WinGuid.parse('faa585ea-6214-4217-afda-7f46de5869b3'), [DynWinRtType.interface(WinGuid.parse('125e7431-f678-4e8e-b670-20a9b06c512d'))]).iid(); const IID_WwwFormUrlDecoder = WinGuid.parse('d45a0451-f225-4542-9296-0e1df5d254df'); let _IWwwFormUrlDecoderRuntimeClassCache; @@ -43,28 +43,28 @@ const _IWwwFormUrlDecoderRuntimeClassFactory = new Proxy({}, { } }); -let _IVectorView_IWwwFormUrlDecoderEntryCache; -const _IVectorView_IWwwFormUrlDecoderEntry = new Proxy({}, { +let _IVectorView_WindowsFoundationIWwwFormUrlDecoderEntry_g58829236a97a8635Cache; +const _IVectorView_WindowsFoundationIWwwFormUrlDecoderEntry_g58829236a97a8635 = new Proxy({}, { get(_target, prop) { - _IVectorView_IWwwFormUrlDecoderEntryCache ??= DynWinRtType.registerInterface( - "IVectorView_IWwwFormUrlDecoderEntry", IID_IVectorView_IWwwFormUrlDecoderEntry) + _IVectorView_WindowsFoundationIWwwFormUrlDecoderEntry_g58829236a97a8635Cache ??= DynWinRtType.registerInterface( + "IVectorView_WindowsFoundationIWwwFormUrlDecoderEntry_g58829236a97a8635", IID_IVectorView_WindowsFoundationIWwwFormUrlDecoderEntry_g58829236a97a8635) .addMethod("GetAt", new DynWinRtMethodSig().addIn(DynWinRtType.u32()).addOut(DynWinRtType.interface(WinGuid.parse('125e7431-f678-4e8e-b670-20a9b06c512d')))) .addMethod("get_Size", new DynWinRtMethodSig().addOut(DynWinRtType.u32())) .addMethod("IndexOf", new DynWinRtMethodSig().addIn(DynWinRtType.interface(WinGuid.parse('125e7431-f678-4e8e-b670-20a9b06c512d'))).addOut(DynWinRtType.u32()).addOut(DynWinRtType.boolType())) .addMethod("GetMany", new DynWinRtMethodSig().addIn(DynWinRtType.u32()).addOutFill(DynWinRtType.arrayType(DynWinRtType.interface(WinGuid.parse('125e7431-f678-4e8e-b670-20a9b06c512d')))).addOut(DynWinRtType.u32())); - const value = _IVectorView_IWwwFormUrlDecoderEntryCache[prop]; - return typeof value === 'function' ? value.bind(_IVectorView_IWwwFormUrlDecoderEntryCache) : value; + const value = _IVectorView_WindowsFoundationIWwwFormUrlDecoderEntry_g58829236a97a8635Cache[prop]; + return typeof value === 'function' ? value.bind(_IVectorView_WindowsFoundationIWwwFormUrlDecoderEntry_g58829236a97a8635Cache) : value; } }); -let _IIterable_IWwwFormUrlDecoderEntryCache; -const _IIterable_IWwwFormUrlDecoderEntry = new Proxy({}, { +let _IIterable_WindowsFoundationIWwwFormUrlDecoderEntry_gd13025e9604dbcdbCache; +const _IIterable_WindowsFoundationIWwwFormUrlDecoderEntry_gd13025e9604dbcdb = new Proxy({}, { get(_target, prop) { - _IIterable_IWwwFormUrlDecoderEntryCache ??= DynWinRtType.registerInterface( - "IIterable_IWwwFormUrlDecoderEntry", IID_IIterable_IWwwFormUrlDecoderEntry) + _IIterable_WindowsFoundationIWwwFormUrlDecoderEntry_gd13025e9604dbcdbCache ??= DynWinRtType.registerInterface( + "IIterable_WindowsFoundationIWwwFormUrlDecoderEntry_gd13025e9604dbcdb", IID_IIterable_WindowsFoundationIWwwFormUrlDecoderEntry_gd13025e9604dbcdb) .addMethod("First", new DynWinRtMethodSig().addOut(DynWinRtType.parameterized(WinGuid.parse('6a79e863-4300-459a-9966-cbb660963ee1'), [DynWinRtType.interface(WinGuid.parse('125e7431-f678-4e8e-b670-20a9b06c512d'))]))); - const value = _IIterable_IWwwFormUrlDecoderEntryCache[prop]; - return typeof value === 'function' ? value.bind(_IIterable_IWwwFormUrlDecoderEntryCache) : value; + const value = _IIterable_WindowsFoundationIWwwFormUrlDecoderEntry_gd13025e9604dbcdbCache[prop]; + return typeof value === 'function' ? value.bind(_IIterable_WindowsFoundationIWwwFormUrlDecoderEntry_gd13025e9604dbcdbCache) : value; } }); @@ -96,13 +96,13 @@ class WwwFormUrlDecoder { return InterfaceClass.from(this._obj); } getAt(index) { - return ((v) => v.isNull() ? null : new (__get_IWwwFormUrlDecoderEntry())(v))(_IVectorView_IWwwFormUrlDecoderEntry.method(6).invoke(this._obj.cast(IID_IVectorView_IWwwFormUrlDecoderEntry), [DynWinRtValue.u32(index)])); + return ((v) => v.isNull() ? null : new (__get_IWwwFormUrlDecoderEntry())(v))(_IVectorView_WindowsFoundationIWwwFormUrlDecoderEntry_g58829236a97a8635.method(6).invoke(this._obj.cast(IID_IVectorView_WindowsFoundationIWwwFormUrlDecoderEntry_g58829236a97a8635), [DynWinRtValue.u32(index)])); } get size() { - return _IVectorView_IWwwFormUrlDecoderEntry.method(7).invoke(this._obj.cast(IID_IVectorView_IWwwFormUrlDecoderEntry), []).toNumber(); + return _IVectorView_WindowsFoundationIWwwFormUrlDecoderEntry_g58829236a97a8635.method(7).invoke(this._obj.cast(IID_IVectorView_WindowsFoundationIWwwFormUrlDecoderEntry_g58829236a97a8635), []).toNumber(); } getMany(startIndex, items) { - return (() => { const _r = _IVectorView_IWwwFormUrlDecoderEntry.method(9).invokeAll(this._obj.cast(IID_IVectorView_IWwwFormUrlDecoderEntry), [DynWinRtValue.u32(startIndex), (Array.isArray(items) ? DynWinRtArray.fromObjectValues(items.map(_i => _unwrap(_i)), DynWinRtType.interface(WinGuid.parse('125e7431-f678-4e8e-b670-20a9b06c512d'))).toValue() : _unwrap(items))]); return _r[0].asArray().toValues().map(v => v.isNull() ? null : new (__get_IWwwFormUrlDecoderEntry())(v)).slice(0, _r[1].toNumber()); })(); + return (() => { const _r = _IVectorView_WindowsFoundationIWwwFormUrlDecoderEntry_g58829236a97a8635.method(9).invokeAll(this._obj.cast(IID_IVectorView_WindowsFoundationIWwwFormUrlDecoderEntry_g58829236a97a8635), [DynWinRtValue.u32(startIndex), (Array.isArray(items) ? DynWinRtArray.fromObjectValues(items.map(_i => _unwrap(_i)), DynWinRtType.interface(WinGuid.parse('125e7431-f678-4e8e-b670-20a9b06c512d'))).toValue() : _unwrap(items))]); return _r[0].asArray().toValues().map(v => v.isNull() ? null : new (__get_IWwwFormUrlDecoderEntry())(v)).slice(0, _r[1].toNumber()); })(); } /** Alias for {@link size}; matches Array.length / TypedArray.length. */ get length() { return this.size; } @@ -128,14 +128,14 @@ class WwwFormUrlDecoder { * Return the index of `value`, or -1 if not found. */ indexOf(value) { - return (() => { const _r = _IVectorView_IWwwFormUrlDecoderEntry.method(8).invokeAll(this._obj.cast(IID_IVectorView_IWwwFormUrlDecoderEntry), [(value == null ? DynWinRtValue.nullValue() : _unwrap(value))]); return _r[1].toBool() ? _r[0].toNumber() : -1; })(); + return (() => { const _r = _IVectorView_WindowsFoundationIWwwFormUrlDecoderEntry_g58829236a97a8635.method(8).invokeAll(this._obj.cast(IID_IVectorView_WindowsFoundationIWwwFormUrlDecoderEntry_g58829236a97a8635), [(value == null ? DynWinRtValue.nullValue() : _unwrap(value))]); return _r[1].toBool() ? _r[0].toNumber() : -1; })(); } first() { - return ((v) => v.isNull() ? null : new (__get_IIterator_IWwwFormUrlDecoderEntry())(v))(_IIterable_IWwwFormUrlDecoderEntry.method(6).invoke(this._obj.cast(IID_IIterable_IWwwFormUrlDecoderEntry), [])); + return ((v) => v.isNull() ? null : new (__get_IIterator_WindowsFoundationIWwwFormUrlDecoderEntry_g498f64075ebd0fce())(v))(_IIterable_WindowsFoundationIWwwFormUrlDecoderEntry_gd13025e9604dbcdb.method(6).invoke(this._obj.cast(IID_IIterable_WindowsFoundationIWwwFormUrlDecoderEntry_gd13025e9604dbcdb), [])); } } -class IVectorView_IWwwFormUrlDecoderEntry { +class IVectorView_WindowsFoundationIWwwFormUrlDecoderEntry_g58829236a97a8635 { _obj; constructor(obj) { @@ -143,19 +143,19 @@ class IVectorView_IWwwFormUrlDecoderEntry { } static from(obj) { - return new IVectorView_IWwwFormUrlDecoderEntry(obj.cast(IID_IVectorView_IWwwFormUrlDecoderEntry)); + return new IVectorView_WindowsFoundationIWwwFormUrlDecoderEntry_g58829236a97a8635(obj.cast(IID_IVectorView_WindowsFoundationIWwwFormUrlDecoderEntry_g58829236a97a8635)); } getAt(index) { - return ((v) => v.isNull() ? null : new (__get_IWwwFormUrlDecoderEntry())(v))(_IVectorView_IWwwFormUrlDecoderEntry.method(6).invoke(this._obj, [DynWinRtValue.u32(index)])); + return ((v) => v.isNull() ? null : new (__get_IWwwFormUrlDecoderEntry())(v))(_IVectorView_WindowsFoundationIWwwFormUrlDecoderEntry_g58829236a97a8635.method(6).invoke(this._obj, [DynWinRtValue.u32(index)])); } get size() { - return _IVectorView_IWwwFormUrlDecoderEntry.method(7).invoke(this._obj, []).toNumber(); + return _IVectorView_WindowsFoundationIWwwFormUrlDecoderEntry_g58829236a97a8635.method(7).invoke(this._obj, []).toNumber(); } getMany(startIndex, items) { - return (() => { const _r = _IVectorView_IWwwFormUrlDecoderEntry.method(9).invokeAll(this._obj, [DynWinRtValue.u32(startIndex), (Array.isArray(items) ? DynWinRtArray.fromObjectValues(items.map(_i => _unwrap(_i)), DynWinRtType.interface(WinGuid.parse('125e7431-f678-4e8e-b670-20a9b06c512d'))).toValue() : _unwrap(items))]); return _r[0].asArray().toValues().map(v => v.isNull() ? null : new (__get_IWwwFormUrlDecoderEntry())(v)).slice(0, _r[1].toNumber()); })(); + return (() => { const _r = _IVectorView_WindowsFoundationIWwwFormUrlDecoderEntry_g58829236a97a8635.method(9).invokeAll(this._obj, [DynWinRtValue.u32(startIndex), (Array.isArray(items) ? DynWinRtArray.fromObjectValues(items.map(_i => _unwrap(_i)), DynWinRtType.interface(WinGuid.parse('125e7431-f678-4e8e-b670-20a9b06c512d'))).toValue() : _unwrap(items))]); return _r[0].asArray().toValues().map(v => v.isNull() ? null : new (__get_IWwwFormUrlDecoderEntry())(v)).slice(0, _r[1].toNumber()); })(); } /** Alias for {@link size}; matches Array.length / TypedArray.length. */ @@ -186,11 +186,11 @@ class IVectorView_IWwwFormUrlDecoderEntry { * Return the index of `value`, or -1 if not found. */ indexOf(value) { - return (() => { const _r = _IVectorView_IWwwFormUrlDecoderEntry.method(8).invokeAll(this._obj, [(value == null ? DynWinRtValue.nullValue() : _unwrap(value))]); return _r[1].toBool() ? _r[0].toNumber() : -1; })(); + return (() => { const _r = _IVectorView_WindowsFoundationIWwwFormUrlDecoderEntry_g58829236a97a8635.method(8).invokeAll(this._obj, [(value == null ? DynWinRtValue.nullValue() : _unwrap(value))]); return _r[1].toBool() ? _r[0].toNumber() : -1; })(); } } -class IIterable_IWwwFormUrlDecoderEntry { +class IIterable_WindowsFoundationIWwwFormUrlDecoderEntry_gd13025e9604dbcdb { _obj; constructor(obj) { @@ -198,16 +198,16 @@ class IIterable_IWwwFormUrlDecoderEntry { } static from(obj) { - return new IIterable_IWwwFormUrlDecoderEntry(obj.cast(IID_IIterable_IWwwFormUrlDecoderEntry)); + return new IIterable_WindowsFoundationIWwwFormUrlDecoderEntry_gd13025e9604dbcdb(obj.cast(IID_IIterable_WindowsFoundationIWwwFormUrlDecoderEntry_gd13025e9604dbcdb)); } first() { - return ((v) => v.isNull() ? null : new (__get_IIterator_IWwwFormUrlDecoderEntry())(v))(_IIterable_IWwwFormUrlDecoderEntry.method(6).invoke(this._obj, [])); + return ((v) => v.isNull() ? null : new (__get_IIterator_WindowsFoundationIWwwFormUrlDecoderEntry_g498f64075ebd0fce())(v))(_IIterable_WindowsFoundationIWwwFormUrlDecoderEntry_gd13025e9604dbcdb.method(6).invoke(this._obj, [])); } [Symbol.iterator]() { return this.first(); } } exports.IID_WwwFormUrlDecoder = IID_WwwFormUrlDecoder; exports.WwwFormUrlDecoder = WwwFormUrlDecoder; -exports.IVectorView_IWwwFormUrlDecoderEntry = IVectorView_IWwwFormUrlDecoderEntry; -exports.IIterable_IWwwFormUrlDecoderEntry = IIterable_IWwwFormUrlDecoderEntry; +exports.IVectorView_WindowsFoundationIWwwFormUrlDecoderEntry_g58829236a97a8635 = IVectorView_WindowsFoundationIWwwFormUrlDecoderEntry_g58829236a97a8635; +exports.IIterable_WindowsFoundationIWwwFormUrlDecoderEntry_gd13025e9604dbcdb = IIterable_WindowsFoundationIWwwFormUrlDecoderEntry_gd13025e9604dbcdb; diff --git a/tools/dynwinrt-codegen/tests/snapshots/uri/IIterator_IWwwFormUrlDecoderEntry.d.ts b/tools/dynwinrt-codegen/tests/snapshots/uri/windows/foundation/collections/IIterator_WindowsFoundationIWwwFormUrlDecoderEntry_g498f64075ebd0fce.d.ts similarity index 57% rename from tools/dynwinrt-codegen/tests/snapshots/uri/IIterator_IWwwFormUrlDecoderEntry.d.ts rename to tools/dynwinrt-codegen/tests/snapshots/uri/windows/foundation/collections/IIterator_WindowsFoundationIWwwFormUrlDecoderEntry_g498f64075ebd0fce.d.ts index 6462b677..84567886 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/uri/IIterator_IWwwFormUrlDecoderEntry.d.ts +++ b/tools/dynwinrt-codegen/tests/snapshots/uri/windows/foundation/collections/IIterator_WindowsFoundationIWwwFormUrlDecoderEntry_g498f64075ebd0fce.d.ts @@ -1,14 +1,14 @@ // Generated by dynwinrt-codegen — do not edit import { WinGuid } from '@microsoft/dynwinrt'; -import { IWwwFormUrlDecoderEntry } from './IWwwFormUrlDecoderEntry.js'; +import { IWwwFormUrlDecoderEntry } from '../IWwwFormUrlDecoderEntry.js'; -export declare const IID_IIterator_IWwwFormUrlDecoderEntry: WinGuid; +export declare const IID_IIterator_WindowsFoundationIWwwFormUrlDecoderEntry_g498f64075ebd0fce: WinGuid; -export declare class IIterator_IWwwFormUrlDecoderEntry { +export declare class IIterator_WindowsFoundationIWwwFormUrlDecoderEntry_g498f64075ebd0fce { private constructor(); /** @internal Cast a raw WinRT object to this interface. */ - static from(obj: any): IIterator_IWwwFormUrlDecoderEntry; + static from(obj: any): IIterator_WindowsFoundationIWwwFormUrlDecoderEntry_g498f64075ebd0fce; get current(): IWwwFormUrlDecoderEntry; diff --git a/tools/dynwinrt-codegen/tests/snapshots/uri/windows/foundation/collections/IIterator_WindowsFoundationIWwwFormUrlDecoderEntry_g498f64075ebd0fce.js b/tools/dynwinrt-codegen/tests/snapshots/uri/windows/foundation/collections/IIterator_WindowsFoundationIWwwFormUrlDecoderEntry_g498f64075ebd0fce.js new file mode 100644 index 00000000..a8096f6f --- /dev/null +++ b/tools/dynwinrt-codegen/tests/snapshots/uri/windows/foundation/collections/IIterator_WindowsFoundationIWwwFormUrlDecoderEntry_g498f64075ebd0fce.js @@ -0,0 +1,64 @@ +// Generated by dynwinrt-codegen — do not edit +const { DynWinRtType, DynWinRtMethodSig, DynWinRtValue, DynWinRtArray, DynWinRtDelegate, WinGuid } = require('@microsoft/dynwinrt'); +require('./../IWwwFormUrlDecoderEntry.js'); +let __m____IWwwFormUrlDecoderEntry_9aa9ab9b; +const __load____IWwwFormUrlDecoderEntry_9aa9ab9b = () => (__m____IWwwFormUrlDecoderEntry_9aa9ab9b ??= require('./../IWwwFormUrlDecoderEntry.js')); +const __get_IWwwFormUrlDecoderEntry = () => __load____IWwwFormUrlDecoderEntry_9aa9ab9b().IWwwFormUrlDecoderEntry; + +const _unwrap = (x) => x?._obj ?? x; + +const IID_IIterator_WindowsFoundationIWwwFormUrlDecoderEntry_g498f64075ebd0fce = DynWinRtType.parameterized(WinGuid.parse('6a79e863-4300-459a-9966-cbb660963ee1'), [DynWinRtType.interface(WinGuid.parse('125e7431-f678-4e8e-b670-20a9b06c512d'))]).iid(); + +let _IIterator_WindowsFoundationIWwwFormUrlDecoderEntry_g498f64075ebd0fceCache; +const _IIterator_WindowsFoundationIWwwFormUrlDecoderEntry_g498f64075ebd0fce = new Proxy({}, { + get(_target, prop) { + _IIterator_WindowsFoundationIWwwFormUrlDecoderEntry_g498f64075ebd0fceCache ??= DynWinRtType.registerInterface( + "IIterator_WindowsFoundationIWwwFormUrlDecoderEntry_g498f64075ebd0fce", IID_IIterator_WindowsFoundationIWwwFormUrlDecoderEntry_g498f64075ebd0fce) + .addMethod("get_Current", new DynWinRtMethodSig().addOut(DynWinRtType.interface(WinGuid.parse('125e7431-f678-4e8e-b670-20a9b06c512d')))) + .addMethod("get_HasCurrent", new DynWinRtMethodSig().addOut(DynWinRtType.boolType())) + .addMethod("MoveNext", new DynWinRtMethodSig().addOut(DynWinRtType.boolType())) + .addMethod("GetMany", new DynWinRtMethodSig().addOutFill(DynWinRtType.arrayType(DynWinRtType.interface(WinGuid.parse('125e7431-f678-4e8e-b670-20a9b06c512d')))).addOut(DynWinRtType.u32())); + const value = _IIterator_WindowsFoundationIWwwFormUrlDecoderEntry_g498f64075ebd0fceCache[prop]; + return typeof value === 'function' ? value.bind(_IIterator_WindowsFoundationIWwwFormUrlDecoderEntry_g498f64075ebd0fceCache) : value; + } +}); + +class IIterator_WindowsFoundationIWwwFormUrlDecoderEntry_g498f64075ebd0fce { + _obj; + + constructor(obj) { + this._obj = obj.cast(IID_IIterator_WindowsFoundationIWwwFormUrlDecoderEntry_g498f64075ebd0fce); + } + + static from(obj) { + return new IIterator_WindowsFoundationIWwwFormUrlDecoderEntry_g498f64075ebd0fce(obj.cast(IID_IIterator_WindowsFoundationIWwwFormUrlDecoderEntry_g498f64075ebd0fce)); + } + + get current() { + return ((v) => v.isNull() ? null : new (__get_IWwwFormUrlDecoderEntry())(v))((() => { const _m = _IIterator_WindowsFoundationIWwwFormUrlDecoderEntry_g498f64075ebd0fce.method(6); return typeof _m.getObj === 'function' ? _m.getObj(this._obj) : _m.invoke(this._obj, []); })()); + } + + get hasCurrent() { + return (() => { const _m = _IIterator_WindowsFoundationIWwwFormUrlDecoderEntry_g498f64075ebd0fce.method(7); return typeof _m.getBool === 'function' ? _m.getBool(this._obj) : _IIterator_WindowsFoundationIWwwFormUrlDecoderEntry_g498f64075ebd0fce.method(7).invoke(this._obj, []).toBool(); })(); + } + + moveNext() { + return _IIterator_WindowsFoundationIWwwFormUrlDecoderEntry_g498f64075ebd0fce.method(8).invoke(this._obj, []).toBool(); + } + + getMany(items) { + return (() => { const _r = _IIterator_WindowsFoundationIWwwFormUrlDecoderEntry_g498f64075ebd0fce.method(9).invokeAll(this._obj, [(Array.isArray(items) ? DynWinRtArray.fromObjectValues(items.map(_i => _unwrap(_i)), DynWinRtType.interface(WinGuid.parse('125e7431-f678-4e8e-b670-20a9b06c512d'))).toValue() : _unwrap(items))]); return _r[0].asArray().toValues().map(v => v.isNull() ? null : new (__get_IWwwFormUrlDecoderEntry())(v)).slice(0, _r[1].toNumber()); })(); + } + + /** JS iterator protocol: returns the current element and advances. */ + next() { + if (!this.hasCurrent) return { value: undefined, done: true }; + const value = this.current; + this.moveNext(); + return { value, done: false }; + } + + [Symbol.iterator]() { return this; } +} +exports.IID_IIterator_WindowsFoundationIWwwFormUrlDecoderEntry_g498f64075ebd0fce = IID_IIterator_WindowsFoundationIWwwFormUrlDecoderEntry_g498f64075ebd0fce; +exports.IIterator_WindowsFoundationIWwwFormUrlDecoderEntry_g498f64075ebd0fce = IIterator_WindowsFoundationIWwwFormUrlDecoderEntry_g498f64075ebd0fce; diff --git a/tools/dynwinrt-codegen/tests/tsc_check_test.rs b/tools/dynwinrt-codegen/tests/tsc_check_test.rs index 33893cc4..7b6c8847 100644 --- a/tools/dynwinrt-codegen/tests/tsc_check_test.rs +++ b/tools/dynwinrt-codegen/tests/tsc_check_test.rs @@ -8,26 +8,56 @@ use std::fs; use std::path::Path; +use std::path::PathBuf; use std::process::Command; -const WINDOWS_WINMD: &str = +const DEFAULT_WINDOWS_WINMD: &str = r"C:\Program Files (x86)\Windows Kits\10\UnionMetadata\10.0.26100.0\Windows.winmd"; #[test] fn generated_dts_passes_tsc_no_emit() { - if !Path::new(WINDOWS_WINMD).exists() { + let require_tsc = std::env::var("DYNWINRT_REQUIRE_TSC").as_deref() == Ok("1"); + let windows_winmd = std::env::var_os("DYNWINRT_WINDOWS_WINMD") + .map(PathBuf::from) + .unwrap_or_else(|| PathBuf::from(DEFAULT_WINDOWS_WINMD)); + if !windows_winmd.is_file() { + assert!( + !require_tsc, + "DYNWINRT_REQUIRE_TSC=1 but Windows metadata is missing at {}", + windows_winmd.display() + ); eprintln!("Skipping: Windows.winmd not found"); return; } - // Check npx is available - let npx_check = Command::new("cmd") - .args(["/c", "npx", "tsc", "--version"]) - .output(); - match npx_check { - Ok(o) if o.status.success() => {} - _ => { - eprintln!("Skipping: npx tsc not available"); + let tsc = std::env::var_os("DYNWINRT_TSC") + .map(PathBuf::from) + .unwrap_or_else(|| { + Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../bindings/js/node_modules/typescript/bin/tsc") + }); + if !tsc.is_file() { + assert!( + !require_tsc, + "DYNWINRT_REQUIRE_TSC=1 but TypeScript compiler is missing at {}", + tsc.display() + ); + eprintln!( + "Skipping: TypeScript compiler is missing at {}", + tsc.display() + ); + return; + } + let tsc_check = Command::new("node").arg(&tsc).arg("--version").output(); + match tsc_check { + Ok(output) if output.status.success() => {} + result => { + assert!( + !require_tsc, + "DYNWINRT_REQUIRE_TSC=1 but node could not run {}: {result:?}", + tsc.display() + ); + eprintln!("Skipping: node could not run {}", tsc.display()); return; } } @@ -51,6 +81,8 @@ fn generated_dts_passes_tsc_no_emit() { "--output", ]) .arg(&tmp) + .arg("--winmd") + .arg(&windows_winmd) .status() .expect("spawn dynwinrt-codegen"); assert!(status.success(), "codegen failed (Uri): {:?}", status); @@ -68,6 +100,8 @@ fn generated_dts_passes_tsc_no_emit() { "--output", ]) .arg(&tmp) + .arg("--winmd") + .arg(&windows_winmd) .status() .expect("spawn dynwinrt-codegen"); assert!( @@ -89,6 +123,8 @@ fn generated_dts_passes_tsc_no_emit() { "--output", ]) .arg(&tmp) + .arg("--winmd") + .arg(&windows_winmd) .status() .expect("spawn dynwinrt-codegen"); assert!(status3.success(), "codegen failed (User): {:?}", status3); @@ -105,6 +141,8 @@ fn generated_dts_passes_tsc_no_emit() { "--output", ]) .arg(&tmp) + .arg("--winmd") + .arg(&windows_winmd) .status() .expect("spawn dynwinrt-codegen"); assert!( @@ -115,10 +153,10 @@ fn generated_dts_passes_tsc_no_emit() { fs::write( tmp.join("constructor-usage.ts"), - r#"import { Uri } from "./Uri.js"; -import { User } from "./User.js"; -import { ContactDate } from "./ContactDate.js"; -import { IReference_UInt32 } from "./IReference_UInt32.js"; + r#"import { Uri } from "./windows/foundation/Uri.js"; +import { User } from "./windows/system/User.js"; +import { ContactDate } from "./windows/application-model/contacts/ContactDate.js"; +import { IReference_UInt32 } from "./windows/foundation/IReference_UInt32.js"; new Uri("https://example.com"); new Uri("https://example.com/base/", "child"); @@ -239,16 +277,9 @@ export declare class WinGuid { } "#).expect("write stub index.d.ts"); - // Run tsc --noEmit (use cmd /c npx since npx is a .cmd on Windows) - let tsc_output = Command::new("cmd") - .args([ - "/c", - "npx", - "tsc", - "--noEmit", - "-p", - tsconfig.to_str().unwrap(), - ]) + let tsc_output = Command::new("node") + .arg(&tsc) + .args(["--noEmit", "-p", tsconfig.to_str().unwrap()]) .current_dir(&tmp) .output() .expect("spawn tsc"); diff --git a/tools/dynwinrt-codegen/tests/win32_com_test.rs b/tools/dynwinrt-codegen/tests/win32_com_test.rs index cc8f9525..6e00603f 100644 --- a/tools/dynwinrt-codegen/tests/win32_com_test.rs +++ b/tools/dynwinrt-codegen/tests/win32_com_test.rs @@ -958,7 +958,8 @@ fn run_codegen_command( } fn assert_mixed_package_shape(output_dir: &Path) { - assert!(output_dir.join("Uri.js").is_file()); + assert!(output_dir.join("windows/foundation/Uri.js").is_file()); + assert!(!output_dir.join("Uri.js").exists()); assert!(output_dir.join("com").join("ITaskbarList3.js").is_file()); assert!(output_dir.join("com").join("package.json").is_file()); @@ -974,7 +975,7 @@ fn assert_mixed_package_shape(output_dir: &Path) { let package = fs::read_to_string(output_dir.join("package.json")).unwrap(); assert!(package.contains("\"type\": \"commonjs\"")); - assert!(package.contains("\"./Uri\"")); + assert!(package.contains("\"./windows/foundation/Uri\"")); assert!(package.contains("\"./com\"")); assert!(package.contains("\"./com/*\"")); assert!(package.contains("\"types\": \"./com/*.d.ts\"")); @@ -4720,10 +4721,17 @@ fn mixed_generation_supports_one_command_and_both_incremental_orders() { run_codegen_command( &metadata, None, - "Windows.Foundation.Uri,Windows.Win32.UI.Shell.ITaskbarList3", + "Windows.Foundation.Uri,Windows.Graphics.DirectX.Direct3D11.IDirect3DSurface,Windows.Win32.UI.Shell.ITaskbarList3", &mixed, ); assert_mixed_package_shape(&mixed); + assert!( + mixed + .join("windows/graphics/direct-x/direct3-d11/IDirect3DSurface.js") + .is_file(), + "mixed COM/WinRT interface request must emit the WinRT interface" + ); + assert!(!mixed.join("IDirect3DSurface.js").exists()); run_codegen_command(&metadata, Some("Windows.Foundation"), "Uri", &winrt_first); run_codegen_command(