@adrifer/winix 0.3.0-preview.4 → 0.3.0-preview.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,125 @@
1
+ import { powerShellLiteral as quote } from "../../helpers/utils.js";
2
+ import { filePathExpression, filePathPrelude, resolveWindowsSource } from "../../helpers/windows.js";
3
+ import { windowsSourcePath } from "./paths.js";
4
+ export function personalizationProperties(values, autoHide) {
5
+ const appBar = autoHide === undefined ? "" : `
6
+ if (-not ('WinixAppBarNative' -as [type])) {
7
+ Add-Type @'
8
+ using System;
9
+ using System.Runtime.InteropServices;
10
+ public static class WinixAppBarNative {
11
+ [StructLayout(LayoutKind.Sequential)]
12
+ public struct Data { public uint size; public IntPtr hwnd; public uint message; public uint edge;
13
+ public int left; public int top; public int right; public int bottom; public IntPtr param; }
14
+ [DllImport("shell32.dll")] public static extern UIntPtr SHAppBarMessage(uint message, ref Data data);
15
+ }
16
+ '@
17
+ }
18
+ $appBar = [WinixAppBarNative+Data]::new()
19
+ $appBar.size = [Runtime.InteropServices.Marshal]::SizeOf($appBar)
20
+ `;
21
+ const prelude = `
22
+ $ErrorActionPreference = 'Stop'
23
+ $values = ConvertFrom-Json ${quote(JSON.stringify(values))}
24
+ ${appBar}
25
+ function Test-WinixPersonalization {
26
+ ${autoHide === undefined ? "" : `if ((([WinixAppBarNative]::SHAppBarMessage(4, [ref]$appBar).ToUInt64() -band 1) -ne 0) -ne $${autoHide}) { return $false }`}
27
+ foreach ($item in $values) {
28
+ $key = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey($item.path)
29
+ if ($null -eq $key) { return $false }
30
+ try {
31
+ if ($key.GetValueNames() -notcontains $item.name -or
32
+ $key.GetValueKind($item.name) -ne [Microsoft.Win32.RegistryValueKind]::DWord -or
33
+ ([long]$key.GetValue($item.name) -band 0xffffffffL) -ne [long]$item.value) { return $false }
34
+ } finally { $key.Dispose() }
35
+ }
36
+ return $true
37
+ }`;
38
+ return {
39
+ getScript: `${prelude}\n@{ InDesiredState = (Test-WinixPersonalization) }`,
40
+ testScript: `${prelude}\nTest-WinixPersonalization`,
41
+ setScript: `${prelude}
42
+ if (Test-WinixPersonalization) { return }
43
+ ${autoHide === undefined ? "" : `
44
+ $state = [WinixAppBarNative]::SHAppBarMessage(4, [ref]$appBar).ToUInt64()
45
+ $appBar.param = [IntPtr](($state -band 2) -bor ${autoHide ? 1 : 0})
46
+ [WinixAppBarNative]::SHAppBarMessage(10, [ref]$appBar) | Out-Null
47
+ `}
48
+ foreach ($item in $values) {
49
+ $key = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey($item.path)
50
+ try {
51
+ $signed = [BitConverter]::ToInt32([BitConverter]::GetBytes([uint32]$item.value), 0)
52
+ $key.SetValue($item.name, $signed, [Microsoft.Win32.RegistryValueKind]::DWord)
53
+ } finally { $key.Dispose() }
54
+ }
55
+ if (-not (Test-WinixPersonalization)) { throw 'Windows personalization verification failed' }
56
+ Write-Warning 'Some Explorer/taskbar/theme preferences take effect after signing out. Winix will not restart Explorer.'`,
57
+ };
58
+ }
59
+ export function wallpaperProperties(wallpaper, configDir) {
60
+ const source = typeof wallpaper.source === "string"
61
+ ? resolveWindowsSource(wallpaper.source, configDir, windowsSourcePath) : wallpaper.source;
62
+ const styles = { Fill: [10, 0], Fit: [6, 0], Stretch: [2, 0], Tile: [0, 1], Center: [0, 0], Span: [22, 0] };
63
+ const [style, tile] = styles[wallpaper.style ?? "Fill"];
64
+ const prelude = `${filePathPrelude().join("\n")}
65
+ $ErrorActionPreference = 'Stop'
66
+ $source = ${filePathExpression(source)}
67
+ if (-not (Test-Path -LiteralPath $source -PathType Leaf)) { throw "Wallpaper image does not exist: $source" }
68
+ $hash = (Get-FileHash -LiteralPath $source -Algorithm SHA256).Hash
69
+ $cache = Join-Path $env:LOCALAPPDATA 'Winix\\wallpapers'
70
+ $target = Join-Path $cache ($hash + [IO.Path]::GetExtension($source))
71
+ $desktop = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey('Control Panel\\Desktop')
72
+ function Test-WinixWallpaper {
73
+ if ($null -eq $desktop) { return $false }
74
+ $image = [string]$desktop.GetValue('WallPaper', '')
75
+ return (Test-Path -LiteralPath $target -PathType Leaf) -and
76
+ (Get-FileHash -LiteralPath $target -Algorithm SHA256).Hash -eq $hash -and
77
+ $image -eq $target -and
78
+ [string]$desktop.GetValue('WallpaperStyle', '') -eq '${style}' -and
79
+ [string]$desktop.GetValue('TileWallpaper', '') -eq '${tile}'
80
+ }`;
81
+ const dispose = "if ($null -ne $desktop) { $desktop.Dispose() }";
82
+ return {
83
+ getScript: `${prelude}\ntry { @{ InDesiredState = (Test-WinixWallpaper) } } finally { ${dispose} }`,
84
+ testScript: `${prelude}\ntry { Test-WinixWallpaper } finally { ${dispose} }`,
85
+ setScript: `${prelude}
86
+ try { $matches = Test-WinixWallpaper } finally { ${dispose} }
87
+ if ($matches) { return }
88
+ Add-Type -AssemblyName System.Drawing
89
+ $image = [System.Drawing.Image]::FromFile($source)
90
+ try {
91
+ if ($image.Width -lt 1 -or $image.Height -lt 1) { throw 'Invalid wallpaper image' }
92
+ } finally { $image.Dispose() }
93
+ New-Item -ItemType Directory -Path $cache -Force | Out-Null
94
+ if (-not (Test-Path -LiteralPath $target)) { [IO.File]::Copy($source, $target, $false) }
95
+ if ((Get-FileHash -LiteralPath $target -Algorithm SHA256).Hash -ne $hash) { throw 'Wallpaper changed or its cache is corrupt' }
96
+ if (-not ('WinixWallpaperNative' -as [type])) {
97
+ Add-Type @'
98
+ using System;
99
+ using System.Runtime.InteropServices;
100
+ public static class WinixWallpaperNative {
101
+ [DllImport("user32.dll", CharSet=CharSet.Unicode, SetLastError=true)]
102
+ public static extern bool SystemParametersInfo(uint action, uint param, string value, uint flags);
103
+ }
104
+ '@
105
+ }
106
+ $key = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Control Panel\\Desktop')
107
+ try {
108
+ $previousStyle = $key.GetValue('WallpaperStyle', $null)
109
+ $previousTile = $key.GetValue('TileWallpaper', $null)
110
+ $key.SetValue('WallpaperStyle', '${style}', [Microsoft.Win32.RegistryValueKind]::String)
111
+ $key.SetValue('TileWallpaper', '${tile}', [Microsoft.Win32.RegistryValueKind]::String)
112
+ } finally { $key.Dispose() }
113
+ if (-not [WinixWallpaperNative]::SystemParametersInfo(20, 0, $target, 3)) {
114
+ $failure = [System.ComponentModel.Win32Exception]::new([Runtime.InteropServices.Marshal]::GetLastWin32Error())
115
+ $key = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Control Panel\\Desktop')
116
+ try {
117
+ if ($null -eq $previousStyle) { $key.DeleteValue('WallpaperStyle', $false) }
118
+ else { $key.SetValue('WallpaperStyle', $previousStyle, [Microsoft.Win32.RegistryValueKind]::String) }
119
+ if ($null -eq $previousTile) { $key.DeleteValue('TileWallpaper', $false) }
120
+ else { $key.SetValue('TileWallpaper', $previousTile, [Microsoft.Win32.RegistryValueKind]::String) }
121
+ } finally { $key.Dispose() }
122
+ throw $failure
123
+ }`,
124
+ };
125
+ }
@@ -1,8 +1,13 @@
1
+ import { evaluate } from "../../evaluator/index.js";
1
2
  import { type WindowsLock, type WindowsPackageVersionResolver, type WindowsModuleVersionResolver } from "../../backends/windows/lockfile.js";
2
3
  import { type WindowsWslImageResolver } from "../../backends/windows/wsl.js";
3
4
  import { type WindowsWslRepositoryResolver } from "../../backends/windows/wsl-setup.js";
4
5
  import { type ActivationPlatform } from "../activation.js";
6
+ import { type WindowsFontResolver } from "../../backends/windows/fonts.js";
5
7
  interface ApplyOptions {
8
+ resolveWindowsFont?: WindowsFontResolver;
9
+ /** Activation-only overrides; the committed lock and inline declarations remain unchanged. */
10
+ windowsPackageVersions?: (hosts: ReturnType<typeof evaluate>, lock: WindowsLock) => Promise<Record<string, string>>;
6
11
  host?: string;
7
12
  dry: boolean;
8
13
  diff: boolean;
@@ -12,6 +12,7 @@ import { resolvePowerShellModuleVersion } from "../../backends/windows/powershel
12
12
  import { resolveNixosWslImage } from "../../backends/windows/wsl.js";
13
13
  import { resolveWslRepository } from "../../backends/windows/wsl-setup.js";
14
14
  import { platformForEvaluatedHost } from "../activation.js";
15
+ import { collectFontSources, resolveWindowsFonts, resolveFontSource } from "../../backends/windows/fonts.js";
15
16
  export async function applyWorkspace(cwd, opts) {
16
17
  const { workspace, configDir } = await loadWorkspace(cwd);
17
18
  let evaluated = evaluate(workspace);
@@ -29,11 +30,17 @@ export async function applyWorkspace(cwd, opts) {
29
30
  for (const host of windowsHosts)
30
31
  validateWindowsWslResources(host.windows);
31
32
  const windowsLock = windowsHosts.length > 0
32
- ? await prepareWindowsLock(configDir, windowsHosts, opts.dry || opts.windowsLockDry === true, opts.resolveWindowsPackageVersion ?? resolveWingetVersion, opts.resolveWindowsModuleVersion ?? resolvePowerShellModuleVersion, opts.resolveWindowsWslImage ?? resolveNixosWslImage, opts.resolveWindowsWslRepository ?? resolveWslRepository)
33
+ ? await prepareWindowsLock(configDir, windowsHosts, opts.dry || opts.windowsLockDry === true, opts.resolveWindowsPackageVersion ?? resolveWingetVersion, opts.resolveWindowsModuleVersion ?? resolvePowerShellModuleVersion, opts.resolveWindowsWslImage ?? resolveNixosWslImage, opts.resolveWindowsWslRepository ?? resolveWslRepository, opts.resolveWindowsFont ?? resolveFontSource)
33
34
  : undefined;
34
35
  const nixOutput = nixHosts.length > 0 ? generateNix(workspace, nixHosts) : undefined;
36
+ const runtimeVersions = windowsLock && opts.windowsPackageVersions
37
+ ? await opts.windowsPackageVersions(windowsHosts, windowsLock) : {};
38
+ const activationLock = windowsLock ? {
39
+ ...windowsLock,
40
+ packages: Object.fromEntries(Object.entries(windowsLock.packages).map(([id, pin]) => [id, runtimeVersions[id] === undefined ? pin : { ...pin, version: runtimeVersions[id] }])),
41
+ } : undefined;
35
42
  const windowsOutput = windowsHosts.length > 0
36
- ? generateWindows(windowsHosts, windowsLock, configDir)
43
+ ? generateWindows(windowsHosts, activationLock, configDir)
37
44
  : undefined;
38
45
  printWarnings(nixOutput?.warnings ?? []);
39
46
  printWarnings(windowsOutput?.warnings ?? []);
@@ -85,7 +92,7 @@ export async function applyWorkspace(cwd, opts) {
85
92
  export async function apply(cwd, opts) {
86
93
  await applyWorkspace(cwd, opts);
87
94
  }
88
- async function prepareWindowsLock(configDir, windowsHosts, dry, resolveVersion, resolveModuleVersion, resolveWslImage, resolveRepository) {
95
+ async function prepareWindowsLock(configDir, windowsHosts, dry, resolveVersion, resolveModuleVersion, resolveWslImage, resolveRepository, resolveFont) {
89
96
  const now = new Date();
90
97
  const lock = readWindowsLock(configDir) ?? emptyWindowsLock(now);
91
98
  const reconciled = reconcileInlinePins(lock, windowsHosts, now);
@@ -95,9 +102,10 @@ async function prepareWindowsLock(configDir, windowsHosts, dry, resolveVersion,
95
102
  ? await resolveWindowsWslImages(modules.lock, resolveWslImage, now, true)
96
103
  : { lock: modules.lock, changed: false };
97
104
  const repositories = resolveWindowsWslRepositories(images.lock, windowsHosts, resolveRepository, now, true);
98
- const changed = windowsLockChanged(lock, repositories.lock);
105
+ const fonts = await resolveWindowsFonts(repositories.lock, collectFontSources(windowsHosts).values(), resolveFont, now, true);
106
+ const changed = windowsLockChanged(lock, fonts.lock);
99
107
  if (!changed)
100
- return repositories.lock;
108
+ return fonts.lock;
101
109
  if (dry) {
102
110
  if (windowsLockChanged(lock, resolved.lock))
103
111
  printWindowsLockDryRun(resolved.resolutions);
@@ -107,9 +115,11 @@ async function prepareWindowsLock(configDir, windowsHosts, dry, resolveVersion,
107
115
  console.warn("Would pin verified NixOS-WSL images for x64/arm64 in winix-windows.lock");
108
116
  if (repositories.changed)
109
117
  console.warn("Would pin WSL setup repository commits in winix-windows.lock");
110
- return repositories.lock;
118
+ if (fonts.changed)
119
+ console.warn("Would pin verified font sources in winix-windows.lock");
120
+ return fonts.lock;
111
121
  }
112
- writeWindowsLock(configDir, repositories.lock);
122
+ writeWindowsLock(configDir, fonts.lock);
113
123
  if (windowsLockChanged(lock, resolved.lock))
114
124
  printWindowsLockUpdate(resolved.resolutions);
115
125
  for (const entry of modules.resolutions)
@@ -118,7 +128,9 @@ async function prepareWindowsLock(configDir, windowsHosts, dry, resolveVersion,
118
128
  console.log("✓ Pinned verified NixOS-WSL images for x64/arm64 in winix-windows.lock");
119
129
  if (repositories.changed)
120
130
  console.log("✓ Pinned WSL setup repository commits in winix-windows.lock");
121
- return repositories.lock;
131
+ if (fonts.changed)
132
+ console.log("✓ Pinned verified font sources in winix-windows.lock");
133
+ return fonts.lock;
122
134
  }
123
135
  function printWindowsLockDryRun(resolutions) {
124
136
  if (resolutions.length === 0) {
@@ -7,6 +7,8 @@ import { loadWorkspace } from "../loader.js";
7
7
  import { runCommand } from "../run.js";
8
8
  import { activationCommand, assertActivationSupported, platformForEvaluatedHost, } from "../activation.js";
9
9
  import { applyWorkspace } from "./apply.js";
10
+ import { readWindowsLock, serializeWindowsLock, writeWindowsLock } from "../../backends/windows/lockfile.js";
11
+ import { compareWindowsPackageVersions, confirmWindowsPackageLockUpdate, effectiveWindowsPackageVersion, } from "../windows-package-versions.js";
10
12
  export async function switchCommand(cwd, opts) {
11
13
  const { workspace, configDir } = await loadWorkspace(cwd);
12
14
  const evaluated = evaluate(workspace);
@@ -21,18 +23,67 @@ export async function switchCommand(cwd, opts) {
21
23
  const statePath = platform === "windows" && process.platform === "win32"
22
24
  ? opts.windowsState?.path ?? windowsStatePath() : undefined;
23
25
  const performSwitch = async () => {
26
+ const adapter = opts.windowsState?.adapter ?? nativeWindowsStateAdapter;
27
+ const requirements = {};
28
+ const activationVersions = {};
29
+ const newer = [];
24
30
  const result = await applyWorkspace(cwd, {
25
31
  host: hostName,
26
32
  dry: opts.dry && platform === "windows",
27
33
  diff: false,
28
34
  windowsLockDry: opts.dry,
35
+ windowsPackageVersions: statePath ? async (hosts, lock) => {
36
+ const versions = {};
37
+ for (const host of hosts) {
38
+ for (const resource of managedWindowsResources(host)) {
39
+ if (resource.kind !== "package")
40
+ continue;
41
+ const pkg = host.windows.packages?.[resource.id];
42
+ const version = pkg?.version ?? lock.packages[resource.id]?.version;
43
+ if (!version)
44
+ throw new Error(`Missing package version: ${resource.id}`);
45
+ const requirement = { version, exact: pkg?.version !== undefined };
46
+ requirements[resourceKey(resource)] = requirement;
47
+ const snapshot = await adapter.inspect(resource);
48
+ if (snapshot !== null && !("version" in snapshot))
49
+ throw new Error(`Invalid package snapshot: ${resource.id}`);
50
+ const installed = snapshot?.version;
51
+ versions[resource.id] = effectiveWindowsPackageVersion(resource.id, requirement, installed);
52
+ activationVersions[resourceKey(resource)] = versions[resource.id];
53
+ if (!requirement.exact && installed !== undefined && compareWindowsPackageVersions(installed, version) > 0) {
54
+ console.log(`Keeping ${resource.id} ${installed} (locked ${version}).`);
55
+ newer.push({ id: resource.id, installed, locked: version });
56
+ }
57
+ }
58
+ }
59
+ return versions;
60
+ } : undefined,
29
61
  });
30
62
  const activationTarget = platform === "windows"
31
63
  ? windowsConfigurationForHost(result.outDir, hostName)
32
64
  : flakeRefForHost(result.outDir, hostName);
33
65
  const command = activationCommand(platform, activationTarget);
34
66
  console.log(`\nRunning: ${command.join(" ")}`);
35
- const activate = () => runCommand(command[0], command.slice(1), { dry: opts.dry });
67
+ const activate = async () => {
68
+ if (statePath && !opts.dry) {
69
+ for (const resource of managedWindowsResources(selected)) {
70
+ if (resource.kind !== "package")
71
+ continue;
72
+ const key = resourceKey(resource);
73
+ const current = await adapter.inspect(resource);
74
+ if (current !== null) {
75
+ if (!("version" in current))
76
+ throw new Error(`Invalid package snapshot: ${resource.id}`);
77
+ effectiveWindowsPackageVersion(resource.id, requirements[key], current.version);
78
+ if (!requirements[key].exact &&
79
+ compareWindowsPackageVersions(current.version, activationVersions[key]) > 0) {
80
+ throw new Error(`Package ${resource.id} updated during switch. Rerun switch to keep ${current.version}; refusing stale activation.`);
81
+ }
82
+ }
83
+ }
84
+ }
85
+ await runCommand(command[0], command.slice(1), { dry: opts.dry });
86
+ };
36
87
  if (statePath) {
37
88
  const desired = managedWindowsResources(selected);
38
89
  const windows = selected.windows;
@@ -50,12 +101,40 @@ export async function switchCommand(cwd, opts) {
50
101
  statePath,
51
102
  owner: await windowsStateOwner(configDir, hostName),
52
103
  desired, definitions,
104
+ packageRequirements: requirements,
53
105
  dry: opts.dry,
54
106
  yes: opts.yes,
55
- adapter: opts.windowsState?.adapter ?? nativeWindowsStateAdapter,
107
+ adapter,
56
108
  lockHeld: true,
57
109
  activate,
58
110
  });
111
+ if (!opts.dry && lock) {
112
+ let expected = serializeWindowsLock(lock);
113
+ for (const candidate of newer) {
114
+ const current = await adapter.inspect({
115
+ kind: "package", id: candidate.id, source: lock.packages[candidate.id].source,
116
+ });
117
+ if (!current || !("version" in current) || current.version !== candidate.installed) {
118
+ console.log(`Not updating lock for ${candidate.id}: installed version changed during activation.`);
119
+ continue;
120
+ }
121
+ if (!await confirmWindowsPackageLockUpdate(candidate.id, candidate.installed, candidate.locked))
122
+ continue;
123
+ const saved = readWindowsLock(configDir);
124
+ if (!saved || serializeWindowsLock(saved) !== expected) {
125
+ throw new Error("winix-windows.lock changed during switch; refusing to overwrite concurrent changes.");
126
+ }
127
+ const now = new Date().toISOString();
128
+ const updated = {
129
+ ...saved, generatedAt: now, packages: {
130
+ ...saved.packages, [candidate.id]: { ...saved.packages[candidate.id], version: candidate.installed, resolvedAt: now },
131
+ },
132
+ };
133
+ writeWindowsLock(configDir, updated);
134
+ expected = serializeWindowsLock(updated);
135
+ console.log(`Updated winix-windows.lock: ${candidate.id} ${candidate.locked} -> ${candidate.installed}.`);
136
+ }
137
+ }
59
138
  }
60
139
  else {
61
140
  if (platform === "windows")
@@ -1,7 +1,9 @@
1
1
  import { type WindowsPackageVersionResolver, type WindowsModuleVersionResolver } from "../../backends/windows/lockfile.js";
2
2
  import { type WindowsWslImageResolver } from "../../backends/windows/wsl.js";
3
3
  import { type WindowsWslRepositoryResolver } from "../../backends/windows/wsl-setup.js";
4
+ import { type WindowsFontResolver } from "../../backends/windows/fonts.js";
4
5
  interface UpdateOptions {
6
+ resolveWindowsFont?: WindowsFontResolver;
5
7
  inputs: string[];
6
8
  dry: boolean;
7
9
  windows?: boolean;
@@ -12,6 +12,7 @@ import { platformForEvaluatedHost } from "../activation.js";
12
12
  import { loadWorkspace } from "../loader.js";
13
13
  import { runCommand } from "../run.js";
14
14
  import { applyWorkspace } from "./apply.js";
15
+ import { collectFontSources, resolveWindowsFonts, resolveFontSource } from "../../backends/windows/fonts.js";
15
16
  export async function update(cwd, opts) {
16
17
  if (opts.windows) {
17
18
  await updateWindowsLock(cwd, opts);
@@ -75,11 +76,13 @@ async function updateWindowsLock(cwd, opts) {
75
76
  const pinned = collectInlinePinnedPackages(windowsHosts);
76
77
  const floating = collectFloatingPackages(windowsHosts, pinned);
77
78
  const modules = collectWindowsModules(windowsHosts);
79
+ const fonts = collectFontSources(windowsHosts);
78
80
  const wslImages = hasWindowsWslDistros(windowsHosts);
79
81
  const wslSetup = windowsHosts.some((host) => host.windows.dsc?.some((resource) => resource.winix?.kind === "wsl-distro" && resource.winix.distro.setup));
80
82
  for (const id of opts.inputs) {
81
83
  if (!floating.has(id) && !pinned.has(id) &&
82
84
  ![...modules.values()].some((module) => module.name.toLowerCase() === id.toLowerCase()) &&
85
+ !(id === "fonts" && fonts.size > 0) &&
83
86
  !(id === "nixos-wsl" && wslImages) && !(id === "wsl-setup" && wslSetup)) {
84
87
  throw new Error(`Windows package, PowerShell module, WSL image or setup repository "${id}" is not declared in this workspace.`);
85
88
  }
@@ -116,6 +119,12 @@ async function updateWindowsLock(cwd, opts) {
116
119
  changed = changed || repositories.changed;
117
120
  console.log(` ${repositories.changed ? "resolved" : "up to date"} WSL setup repository commits (first-run only)`);
118
121
  }
122
+ if (fonts.size > 0 && (opts.inputs.length === 0 || opts.inputs.includes("fonts"))) {
123
+ const result = await resolveWindowsFonts(lock, fonts.values(), opts.resolveWindowsFont ?? resolveFontSource, now);
124
+ lock = result.lock;
125
+ changed = changed || result.changed;
126
+ console.log(` ${result.changed ? "resolved" : "up to date"} font sources`);
127
+ }
119
128
  for (const resolution of resolved.resolutions) {
120
129
  if (resolution.status === "up-to-date") {
121
130
  console.log(` up to date ${resolution.id} ${resolution.source} ${resolution.version}`);
package/dist/cli/index.js CHANGED
@@ -13,6 +13,7 @@ import { renderSkill } from "../skill.js";
13
13
  import { bootstrapCheckout, runCheckout } from "./commands/bootstrap.js";
14
14
  import { forgetWindowsResource, windowsStatePath, listWindowsOwners, migrateWindowsOwner, windowsStateOwner, } from "./windows-state.js";
15
15
  import { findConfig } from "./loader.js";
16
+ import { nerdFontsCatalog } from "../backends/windows/fonts.js";
16
17
  if (process.argv[2] === "run") {
17
18
  try {
18
19
  await runCheckout(process.cwd(), process.argv.slice(3));
@@ -27,6 +28,7 @@ const { positionals, values } = parseArgs({
27
28
  allowPositionals: true,
28
29
  options: {
29
30
  host: { type: "string" },
31
+ provider: { type: "string" },
30
32
  dry: { type: "boolean", default: false },
31
33
  yes: { type: "boolean", short: "y", default: false },
32
34
  diff: { type: "boolean", default: false },
@@ -67,6 +69,7 @@ Commands:
67
69
  switch Generate output and run the host activation command
68
70
  update Update generated flake.lock and copy it to project root
69
71
  inspect Print host composition and fragment graph
72
+ fonts search [query] --provider nerd-fonts Search official font release IDs
70
73
  state forget Release Windows removal ownership without deleting a resource
71
74
  state owners List Windows applied-state owners and their migration IDs
72
75
  state migrate-owner <id> Transfer an old owner's requirements to this checkout/--host
@@ -110,6 +113,25 @@ if (values.yes && command !== "switch" && command !== "bootstrap" &&
110
113
  process.exit(2);
111
114
  }
112
115
  switch (command) {
116
+ case "fonts":
117
+ try {
118
+ if (positionals[1] !== "search" || positionals.length > 3 || values.provider !== "nerd-fonts") {
119
+ throw new Error("Usage: winix fonts search [query] --provider nerd-fonts");
120
+ }
121
+ const catalog = await nerdFontsCatalog();
122
+ const query = positionals[2]?.toLowerCase() ?? "";
123
+ const fonts = catalog.fonts.filter((font) => font.family.toLowerCase().includes(query));
124
+ if (!fonts.length)
125
+ throw new Error(`No Nerd Fonts IDs match "${query}"`);
126
+ console.log(`Nerd Fonts ${catalog.version} (download IDs, not installed family names):`);
127
+ for (const font of fonts)
128
+ console.log(` ${font.family}`);
129
+ }
130
+ catch (error) {
131
+ console.error(`Error: ${error.message}`);
132
+ process.exit(1);
133
+ }
134
+ break;
113
135
  case "bootstrap":
114
136
  try {
115
137
  await bootstrapCheckout(cwd, {
@@ -0,0 +1,8 @@
1
+ /** Only dotted numeric versions have an unambiguous ordering across Windows installers. */
2
+ export declare function compareWindowsPackageVersions(left: string, right: string): number;
3
+ export interface WindowsPackageRequirement {
4
+ version: string;
5
+ exact: boolean;
6
+ }
7
+ export declare function effectiveWindowsPackageVersion(id: string, requirement: WindowsPackageRequirement, installed?: string): string;
8
+ export declare function confirmWindowsPackageLockUpdate(id: string, installed: string, locked: string): Promise<boolean>;
@@ -0,0 +1,43 @@
1
+ import { createInterface } from "node:readline/promises";
2
+ /** Only dotted numeric versions have an unambiguous ordering across Windows installers. */
3
+ export function compareWindowsPackageVersions(left, right) {
4
+ if (left === right)
5
+ return 0;
6
+ if (!/^\d+(?:\.\d+)*$/.test(left) || !/^\d+(?:\.\d+)*$/.test(right)) {
7
+ throw new Error(`Cannot reliably compare Windows package versions "${left}" and "${right}". Declare an exact version or resolve the package version explicitly.`);
8
+ }
9
+ const a = left.split(".").map(BigInt);
10
+ const b = right.split(".").map(BigInt);
11
+ for (let index = 0; index < Math.max(a.length, b.length); index++) {
12
+ const difference = (a[index] ?? 0n) - (b[index] ?? 0n);
13
+ if (difference !== 0n)
14
+ return difference > 0n ? 1 : -1;
15
+ }
16
+ return 0;
17
+ }
18
+ export function effectiveWindowsPackageVersion(id, requirement, installed) {
19
+ if (installed === undefined)
20
+ return requirement.version;
21
+ if (requirement.exact) {
22
+ if (installed !== requirement.version) {
23
+ throw new Error(`Exact version mismatch for ${id}: installed ${installed}, required ${requirement.version}. Resolve it explicitly; Winix will not silently replace or downgrade it.`);
24
+ }
25
+ return requirement.version;
26
+ }
27
+ return compareWindowsPackageVersions(installed, requirement.version) >= 0 ? installed : requirement.version;
28
+ }
29
+ export async function confirmWindowsPackageLockUpdate(id, installed, locked) {
30
+ if (!process.stdin.isTTY || !process.stdout.isTTY)
31
+ return false;
32
+ const prompt = createInterface({ input: process.stdin, output: process.stdout });
33
+ const controller = new AbortController();
34
+ prompt.once("close", () => controller.abort());
35
+ prompt.once("SIGINT", () => controller.abort());
36
+ try {
37
+ const answer = await prompt.question(`${id}: installed ${installed}, locked ${locked}. Update winix-windows.lock to ${installed}? [y/N] `, { signal: controller.signal });
38
+ return /^(y|yes)$/i.test(answer.trim());
39
+ }
40
+ finally {
41
+ prompt.close();
42
+ }
43
+ }
@@ -1,4 +1,5 @@
1
1
  import type { EvaluatedHost } from "../evaluator/index.js";
2
+ import { type WindowsPackageRequirement } from "./windows-package-versions.js";
2
3
  export type ManagedResource = {
3
4
  kind: "startup";
4
5
  name: string;
@@ -18,6 +19,7 @@ interface Entry {
18
19
  owned: boolean;
19
20
  snapshot: ResourceSnapshot;
20
21
  definition: string;
22
+ packageExact?: boolean;
21
23
  }
22
24
  interface AppliedState {
23
25
  version: 1;
@@ -28,6 +30,7 @@ export interface WindowsStateAdapter {
28
30
  remove(resource: ManagedResource, snapshot: NonNullable<ResourceSnapshot>): Promise<void>;
29
31
  }
30
32
  export interface ReconcileOptions {
33
+ packageRequirements?: Record<string, WindowsPackageRequirement>;
31
34
  statePath: string;
32
35
  owner: string;
33
36
  desired: ManagedResource[];
@@ -6,6 +6,7 @@ import { dirname, join } from "node:path";
6
6
  import { createInterface } from "node:readline/promises";
7
7
  import { powerShellLiteral } from "../helpers/utils.js";
8
8
  import { runCommand } from "./run.js";
9
+ import { compareWindowsPackageVersions, effectiveWindowsPackageVersion } from "./windows-package-versions.js";
9
10
  export function resourceKey(resource) {
10
11
  return JSON.stringify(resource.kind === "startup"
11
12
  ? ["startup", resource.name.toLowerCase()]
@@ -99,6 +100,7 @@ export function parseAppliedState(text) {
99
100
  key !== resourceKey(entry.resource) || typeof entry.owned !== "boolean" ||
100
101
  typeof entry.definition !== "string" ||
101
102
  !Array.isArray(entry.owners) || !entry.owners.every((owner) => typeof owner === "string") ||
103
+ (entry.packageExact !== undefined && typeof entry.packageExact !== "boolean") ||
102
104
  !(entry.snapshot === null || (entry.resource.kind === "startup"
103
105
  ? typeof entry.snapshot?.fingerprint === "string" && /^[a-f0-9]{64}$/.test(entry.snapshot.fingerprint)
104
106
  : typeof entry.snapshot?.version === "string" && entry.snapshot.version.length > 0))) {
@@ -207,14 +209,31 @@ export async function reconcileWindows(opts) {
207
209
  const current = await opts.adapter.inspect(resource);
208
210
  before.set(key, current);
209
211
  const entry = state.entries[key];
212
+ const requirement = resource.kind === "package" ? opts.packageRequirements?.[key] : undefined;
213
+ if (requirement && current && "version" in current) {
214
+ effectiveWindowsPackageVersion(resource.kind === "package" ? resource.id : key, requirement, current.version);
215
+ }
210
216
  if (typeof opts.definitions[key] !== "string")
211
217
  throw new Error(`Missing resource definition: ${key}`);
212
218
  if (entry?.owners.some((owner) => owner !== opts.owner) && entry.definition !== opts.definitions[key]) {
213
219
  throw new Error(`Conflicting declaration for resource required by another workspace/host: ${key}. ` +
214
220
  "Run winix state owners; after a checkout move or host rename, explicitly preview state migrate-owner <id> --host <name> --dry.");
215
221
  }
222
+ if (requirement && entry?.owners.some((owner) => owner !== opts.owner)) {
223
+ if (entry.packageExact !== undefined && entry.packageExact !== requirement.exact) {
224
+ throw new Error(`Conflicting exact/minimum package policies across workspace/hosts: ${key}`);
225
+ }
226
+ if (!sameSnapshot(current, entry.snapshot) && entry.packageExact !== false) {
227
+ throw new Error(`Package changed while required by another exact or legacy workspace/host: ${key}`);
228
+ }
229
+ }
216
230
  if (entry?.owned && current !== null && !sameSnapshot(current, entry.snapshot)) {
217
- throw new Error(`Managed resource changed outside Winix: ${key}. Restore it or explicitly resolve ownership before activation.`);
231
+ const upgrade = requirement && !requirement.exact && "version" in current &&
232
+ entry.snapshot && "version" in entry.snapshot &&
233
+ compareWindowsPackageVersions(current.version, entry.snapshot.version) > 0;
234
+ if (!upgrade)
235
+ throw new Error(`Managed resource changed outside Winix: ${key}. Restore it or explicitly resolve ownership before activation.`);
236
+ report(`Keeping externally upgraded package: ${key} ${current.version}`);
218
237
  }
219
238
  }
220
239
  const removals = [];
@@ -253,8 +272,25 @@ export async function reconcileWindows(opts) {
253
272
  if (current === null)
254
273
  throw new Error(`Activation succeeded but managed resource is missing: ${key}`);
255
274
  const entry = state.entries[key];
275
+ const requirement = resource.kind === "package" ? opts.packageRequirements?.[key] : undefined;
276
+ if (requirement) {
277
+ if (!("version" in current) || (requirement.exact
278
+ ? current.version !== requirement.version
279
+ : compareWindowsPackageVersions(current.version, requirement.version) < 0)) {
280
+ throw new Error(`Activation did not satisfy package version requirement: ${key}`);
281
+ }
282
+ const initial = before.get(key);
283
+ if (!requirement.exact && initial && "version" in initial &&
284
+ compareWindowsPackageVersions(current.version, initial.version) < 0) {
285
+ throw new Error(`Activation unexpectedly downgraded package: ${key}`);
286
+ }
287
+ }
256
288
  if (entry && entry.owners.some((owner) => owner !== opts.owner) && !sameSnapshot(current, entry.snapshot)) {
257
- throw new Error(`Activation changed a resource required by another workspace/host: ${key}`);
289
+ const upgrade = requirement && !requirement.exact && entry.packageExact === false && "version" in current &&
290
+ entry.snapshot && "version" in entry.snapshot &&
291
+ compareWindowsPackageVersions(current.version, entry.snapshot.version) > 0;
292
+ if (!upgrade)
293
+ throw new Error(`Activation changed a resource required by another workspace/host: ${key}`);
258
294
  }
259
295
  after.set(key, current);
260
296
  }
@@ -272,6 +308,9 @@ export async function reconcileWindows(opts) {
272
308
  (resource.kind === "startup" && !sameSnapshot(initial, current)),
273
309
  snapshot: current,
274
310
  definition: opts.definitions[key],
311
+ ...(resource.kind === "package" && opts.packageRequirements?.[key]
312
+ ? { packageExact: opts.packageRequirements[key].exact }
313
+ : previous?.packageExact === undefined ? {} : { packageExact: previous.packageExact }),
275
314
  };
276
315
  }
277
316
  await saveState(opts.statePath, state);
@@ -0,0 +1,10 @@
1
+ import type { WinFontSource, WinPersonalization, WinWallpaper } from "../types/windows.js";
2
+ export declare function fontHttpsUrl(value: string): string;
3
+ export declare function validateFontSources(sources: WinFontSource[]): void;
4
+ export declare function validateWallpaper(wallpaper: WinWallpaper): void;
5
+ export interface PersonalizationRegistryValue {
6
+ path: string;
7
+ name: string;
8
+ value: number;
9
+ }
10
+ export declare function personalizationValues(options: WinPersonalization): PersonalizationRegistryValue[];