@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.
package/README.md CHANGED
@@ -960,6 +960,74 @@ as `.lnk.bak` and refuses backup collisions, while `force: true` opts into
960
960
  replacement without a backup. A new shortcut is staged and verified before
961
961
  replacing the old one. Keep names unique per host.
962
962
 
963
+ ### Windows personalization and fonts
964
+
965
+ These helpers manage the current Windows user without requiring elevation:
966
+
967
+ ```ts
968
+ windows.wallpaper({ source: "../wallpapers/desktop.jpg", style: "Fill" });
969
+ windows.personalization({
970
+ accentColor: "#336699",
971
+ explorer: { showExtensions: true, showHiddenFiles: false, openTo: "ThisPC" },
972
+ taskbar: { autoHide: false, search: "Hidden", taskView: true, widgets: false },
973
+ });
974
+ windows.fonts({
975
+ sources: [
976
+ "../fonts/MyFont-Regular.ttf",
977
+ { url: "https://example.com/releases/v1/fonts.zip", files: ["**/*.ttf"] },
978
+ { provider: "nerd-fonts", family: "JetBrainsMono" },
979
+ ],
980
+ });
981
+ ```
982
+
983
+ Wallpaper accepts a local path or `windows.knownFolder.*` path. Relative image
984
+ and font paths resolve from `winix.config.ts`, including Windows and WSL path
985
+ conversion. Wallpaper images are cached by content hash, so editing the source
986
+ image is detected. Styles are `Fill` (default), `Fit`, `Stretch`, `Tile`, `Center`,
987
+ and `Span`; this is one desktop background, not per-monitor image assignment.
988
+
989
+ Personalization only changes declared values. `accentColor` is `#RRGGBB` and
990
+ disables automatic accent coloring. Explorer `openTo` accepts `ThisPC` or `Home`;
991
+ hidden files does not expose protected operating-system files. Taskbar `search`
992
+ accepts `Hidden`, `Icon`, `IconAndLabel`, or `Box`. Explorer/taskbar/accent values
993
+ depend on Windows version and policy and may require signing out; Winix never
994
+ restarts Explorer. Existing `windows.setting()` theme settings remain available.
995
+ Avoid declaring conflicting automatic accent coloring in both helpers.
996
+
997
+ Fonts support local `.ttf`/`.otf` files, HTTPS `.ttf`/`.otf` downloads, and ZIP
998
+ archives. ZIP `files` accepts exact member paths or `**/*.ttf` / `**/*.otf`;
999
+ omitting it selects all font files. Unsafe archives, missing selections and
1000
+ conflicting filenames fail explicitly. Downloads and expanded archives have
1001
+ size limits. Remote sources must not contain credentials. An optional `sha256`
1002
+ provides an independently trusted checksum; otherwise the first resolution
1003
+ records the upstream digest or the downloaded bytes (trust on first use).
1004
+
1005
+ Remote fonts have a separate `fonts` section in `winix-windows.lock`. First
1006
+ apply resolves missing entries; subsequent apply reuses them without a catalog
1007
+ query. `winix update --windows fonts` refreshes only font pins; `--dry` never
1008
+ writes pins or installs fonts. Installation verifies checksums and caches
1009
+ downloads in Local AppData. Nerd Fonts IDs come from official release ZIP
1010
+ assets, not a handwritten registry:
1011
+
1012
+ ```sh
1013
+ winix fonts search JetBrains --provider nerd-fonts
1014
+ winix update --windows fonts --dry
1015
+ ```
1016
+
1017
+ Nerd Fonts is the only built-in provider. Its optional `version: "vX.Y.Z"` selects
1018
+ an exact upstream release; otherwise latest resolves once and stays locked.
1019
+ Provider IDs, archive filenames and installed family names differ. Installation
1020
+ reports family names from font metadata; configure Terminal/editors separately
1021
+ to select them. Fonts are installed and registered for the current user,
1022
+ identical files are reused, and differing existing files/registry entries are
1023
+ not overwritten. Updating a ZIP pin may therefore require explicitly resolving
1024
+ an existing font collision. Font removal/cleanup is not tracked; deleting a
1025
+ declaration leaves installed fonts and caches intact.
1026
+
1027
+ These helpers emit idempotent DSC PowerShell resources. Native desktop/font
1028
+ activation has not been rehearsed on a shared machine; automated checks cover
1029
+ authoring, locking, generated scripts and isolated archive handling.
1030
+
963
1031
  ### Windows removal and ownership
964
1032
 
965
1033
  Native Windows `winix switch` keeps a separate applied-state inventory under
@@ -1005,9 +1073,30 @@ cancels the whole switch without activation or cleanup. Switches without removal
1005
1073
  and `--dry` do not prompt. Use `winix switch --yes` (or `-y`) to accept removals
1006
1074
  for automation; noninteractive switches with removals require this flag.
1007
1075
 
1008
- Startup file hashes and installed package versions detect drift. External edits
1009
- or version changes block reconciliation rather than silently deleting or
1010
- overwriting managed resources. Restore the recorded resource, or explicitly
1076
+ During native Windows `switch`, a package without an inline `version` uses its
1077
+ lock as a minimum version and fresh-install target. An absent package installs
1078
+ the lock; an older installed version upgrades; a newer installed version is kept
1079
+ and reported. The generated activation document targets that installed version,
1080
+ not the older lock. External upgrades of owned packages retain ownership and
1081
+ refresh the observed snapshot after successful activation. Pre-installed packages
1082
+ remain unowned even when upgraded by Winix.
1083
+
1084
+ An inline declaration such as `windows.package({ id: "Git.Git", version: "2.44.0" })`
1085
+ is exact. Installed version mismatches stop before activation, without an
1086
+ automatic downgrade. Unequal versions that are not dotted numeric values cannot
1087
+ be reliably ordered and fail with instructions to resolve them explicitly.
1088
+
1089
+ After a successful interactive switch that kept a newer floating package,
1090
+ Winix asks `Update winix-windows.lock to <version>? [y/N]`. Declining keeps the
1091
+ lock and still completes the switch. Dry/noninteractive runs never ask or
1092
+ update observed-version pins; `--yes` confirms removals, not lock updates.
1093
+ Normal missing-pin resolution remains unchanged. These defaults apply to
1094
+ `winix switch`, not direct generated-script/DSC activation or plain `apply`.
1095
+
1096
+ Startup file hashes and installed package versions still protect removals.
1097
+ External shortcut edits, package downgrades, and exact-pin drift block
1098
+ reconciliation rather than silently deleting or overwriting managed resources.
1099
+ Restore the recorded resource, or explicitly
1011
1100
  release Winix's removal rights without deleting anything:
1012
1101
 
1013
1102
  ```powershell
@@ -0,0 +1 @@
1
+ export declare const fontInstallPrelude: string;
@@ -0,0 +1,206 @@
1
+ export const fontInstallPrelude = String.raw `
2
+ function Get-WinixFontRegistry {
3
+ return [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey('Software\Microsoft\Windows NT\CurrentVersion\Fonts')
4
+ }
5
+ function Test-WinixFonts {
6
+ if (-not (Test-Path -LiteralPath $manifest -PathType Leaf)) { return $false }
7
+ $record = Get-Content -LiteralPath $manifest -Raw | ConvertFrom-Json
8
+ if ($record.version -ne 1 -or @($record.fonts).Count -eq 0) { throw 'Invalid Winix font manifest' }
9
+ foreach ($source in $plan) {
10
+ if ($source.path) {
11
+ $path = [Environment]::ExpandEnvironmentVariables($source.path)
12
+ if (-not (Test-Path -LiteralPath $path -PathType Leaf)) { throw "Local font does not exist: $path" }
13
+ $hash = (Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash
14
+ if (-not @($record.sources | Where-Object { $_.path -eq $source.path -and $_.sha256 -eq $hash }).Count) { return $false }
15
+ }
16
+ $destination = Join-Path $env:LOCALAPPDATA 'Microsoft\Windows\Fonts'
17
+ foreach ($font in $record.fonts) {
18
+ if (-not $font.name -or [IO.Path]::GetFileName($font.name) -ne $font.name -or
19
+ $font.path -ne (Join-Path $destination $font.name) -or $font.sha256 -notmatch '^[a-f0-9]{64}$') {
20
+ throw 'Invalid Winix font manifest entry'
21
+ }
22
+ }
23
+ }
24
+ $registry = Get-WinixFontRegistry
25
+ if ($null -eq $registry) { return $false }
26
+ try {
27
+ foreach ($font in $record.fonts) {
28
+ if (-not (Test-Path -LiteralPath $font.path -PathType Leaf) -or
29
+ (Get-FileHash -LiteralPath $font.path -Algorithm SHA256).Hash -ne $font.sha256 -or
30
+ $registry.GetValue($font.name) -ne $font.path) { return $false }
31
+ }
32
+ } finally { $registry.Dispose() }
33
+ return $true
34
+ }
35
+ function Get-WinixFontDownload($source) {
36
+ $cache = Join-Path $env:LOCALAPPDATA 'Winix\cache\fonts'
37
+ New-Item -ItemType Directory -Path $cache -Force | Out-Null
38
+ $target = Join-Path $cache ($source.sha256 + '.' + $source.format)
39
+ if (Test-Path -LiteralPath $target -PathType Leaf) {
40
+ if ((Get-FileHash -LiteralPath $target -Algorithm SHA256).Hash -ne $source.sha256) { throw "Corrupt font cache: $target" }
41
+ return $target
42
+ }
43
+ $temporary = Join-Path $cache ([guid]::NewGuid().ToString() + '.download')
44
+ $client = [Net.Http.HttpClient]::new([Net.Http.HttpClientHandler]@{ AllowAutoRedirect = $false })
45
+ $client.Timeout = [TimeSpan]::FromSeconds(60)
46
+ try {
47
+ $uri = [uri]$source.url
48
+ for ($redirect = 0; $redirect -le 5; $redirect++) {
49
+ if ($uri.Scheme -ne 'https' -or $uri.UserInfo) { throw 'Unsafe font download URL' }
50
+ $response = $client.GetAsync($uri, [Net.Http.HttpCompletionOption]::ResponseHeadersRead).GetAwaiter().GetResult()
51
+ if ([int]$response.StatusCode -in @(301,302,303,307,308)) {
52
+ try {
53
+ if ($null -eq $response.Headers.Location) { throw 'Font redirect has no location' }
54
+ $uri = [uri]::new($uri, $response.Headers.Location)
55
+ } finally { $response.Dispose() }
56
+ continue
57
+ }
58
+ try {
59
+ $response.EnsureSuccessStatusCode() | Out-Null
60
+ $inputStream = $response.Content.ReadAsStreamAsync().GetAwaiter().GetResult()
61
+ $outputStream = [IO.File]::Open($temporary, [IO.FileMode]::CreateNew)
62
+ try {
63
+ $buffer = [byte[]]::new(65536)
64
+ $total = 0L
65
+ while (($count = $inputStream.Read($buffer, 0, $buffer.Length)) -gt 0) {
66
+ $total += $count
67
+ if ($total -gt 134217728) { throw 'Font download exceeds 128 MiB' }
68
+ $outputStream.Write($buffer, 0, $count)
69
+ }
70
+ } finally { $outputStream.Dispose(); $inputStream.Dispose() }
71
+ } finally { $response.Dispose() }
72
+ if ((Get-FileHash -LiteralPath $temporary -Algorithm SHA256).Hash -ne $source.sha256) { throw 'Font checksum mismatch' }
73
+ [IO.File]::Move($temporary, $target, $false)
74
+ return $target
75
+ }
76
+ throw 'Too many font redirects'
77
+ } finally {
78
+ $client.Dispose()
79
+ if (Test-Path -LiteralPath $temporary) { Remove-Item -LiteralPath $temporary -Force }
80
+ }
81
+ }
82
+ function Expand-WinixFonts([string]$archive, [string]$destination, $selectors) {
83
+ $zip = [IO.Compression.ZipFile]::OpenRead($archive)
84
+ $result = [Collections.Generic.List[string]]::new()
85
+ try {
86
+ if ($zip.Entries.Count -gt 4096) { throw 'Font archive has too many entries' }
87
+ $total = 0L
88
+ foreach ($entry in $zip.Entries) {
89
+ $name = $entry.FullName
90
+ if ($name.StartsWith('/') -or $name.Contains('\') -or $name.Contains(':') -or
91
+ $name.Contains([char]0) -or ($name.Split('/') -contains '..') -or ($name.Split('/') -contains '.') -or
92
+ (($entry.ExternalAttributes -shr 16) -band 0xf000) -eq 0xa000) { throw "Unsafe font ZIP entry: $name" }
93
+ if (-not $entry.Name) { continue }
94
+ $total += $entry.Length
95
+ if ($total -gt 268435456) { throw 'Font archive exceeds 256 MiB expanded' }
96
+ if ([IO.Path]::GetExtension($name) -notin @('.ttf','.otf')) { continue }
97
+ $selected = $false
98
+ foreach ($selector in $selectors) {
99
+ if (($selector -eq '**/*.ttf' -and $name.EndsWith('.ttf', [StringComparison]::OrdinalIgnoreCase)) -or
100
+ ($selector -eq '**/*.otf' -and $name.EndsWith('.otf', [StringComparison]::OrdinalIgnoreCase)) -or
101
+ $selector -ceq $name) { $selected = $true }
102
+ }
103
+ if (-not $selected) { continue }
104
+ $path = Join-Path $destination $entry.Name
105
+ if (Test-Path -LiteralPath $path) { throw "Duplicate font filename: $($entry.Name)" }
106
+ [IO.Compression.ZipFileExtensions]::ExtractToFile($entry, $path, $false)
107
+ $result.Add($path)
108
+ }
109
+ if ($result.Count -eq 0) { throw 'Font archive contains no matching TTF/OTF files' }
110
+ foreach ($selector in $selectors) {
111
+ if (-not $selector.StartsWith('**/') -and -not @($zip.Entries | Where-Object { $_.FullName -ceq $selector }).Count) {
112
+ throw "Font ZIP member does not exist: $selector"
113
+ }
114
+ }
115
+ return $result.ToArray()
116
+ } finally { $zip.Dispose() }
117
+ }
118
+ function Install-WinixFonts {
119
+ $stageRoot = Join-Path $env:LOCALAPPDATA 'Winix\fonts'
120
+ New-Item -ItemType Directory -Path $stageRoot -Force | Out-Null
121
+ $stage = Join-Path $stageRoot ([guid]::NewGuid().ToString())
122
+ New-Item -ItemType Directory -Path $stage | Out-Null
123
+ $files = [Collections.Generic.List[string]]::new()
124
+ $localSources = [Collections.Generic.List[object]]::new()
125
+ try {
126
+ foreach ($source in $plan) {
127
+ if ($source.path) {
128
+ $path = [Environment]::ExpandEnvironmentVariables($source.path)
129
+ if (-not (Test-Path -LiteralPath $path -PathType Leaf)) { throw "Font file does not exist: $path" }
130
+ $files.Add($path)
131
+ $localSources.Add(@{ path = $source.path; sha256 = (Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash })
132
+ } else {
133
+ $download = Get-WinixFontDownload $source
134
+ if ($source.format -eq 'zip') {
135
+ $directory = Join-Path $stage ([guid]::NewGuid().ToString())
136
+ New-Item -ItemType Directory -Path $directory | Out-Null
137
+ foreach ($path in @(Expand-WinixFonts $download $directory $source.files)) { $files.Add($path) }
138
+ } else { $files.Add($download) }
139
+ }
140
+ }
141
+ Add-Type -AssemblyName System.Drawing
142
+ $destination = Join-Path $env:LOCALAPPDATA 'Microsoft\Windows\Fonts'
143
+ $prepared = @{}
144
+ $registry = Get-WinixFontRegistry
145
+ try {
146
+ foreach ($path in $files) {
147
+ $name = [IO.Path]::GetFileName($path)
148
+ $hash = (Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash
149
+ $target = Join-Path $destination $name
150
+ if ($prepared.ContainsKey($name)) {
151
+ if ($prepared[$name].sha256 -ne $hash) { throw "Conflicting font filename: $name" }
152
+ continue
153
+ }
154
+ if ((Test-Path -LiteralPath $target) -and
155
+ ((Get-Item -LiteralPath $target).Attributes -band [IO.FileAttributes]::ReparsePoint)) { throw "Font target is a link: $target" }
156
+ if ((Test-Path -LiteralPath $target) -and
157
+ (Get-FileHash -LiteralPath $target -Algorithm SHA256).Hash -ne $hash) { throw "Font replacement refused: $target" }
158
+ $registered = if ($null -ne $registry) { $registry.GetValue($name) } else { $null }
159
+ if ($null -ne $registered -and $registered -ne $target) { throw "Font registry collision: $name" }
160
+ $collection = [Drawing.Text.PrivateFontCollection]::new()
161
+ try {
162
+ $collection.AddFontFile($path)
163
+ $families = @($collection.Families | ForEach-Object { $_.Name })
164
+ if (-not $families.Count) { throw "Invalid font file: $path" }
165
+ } finally { $collection.Dispose() }
166
+ $prepared[$name] = @{ name = $name; path = $target; source = $path; sha256 = $hash; families = $families }
167
+ }
168
+ } finally { if ($null -ne $registry) { $registry.Dispose() } }
169
+ if (-not ('WinixFontNative' -as [type])) {
170
+ Add-Type @'
171
+ using System;
172
+ using System.Runtime.InteropServices;
173
+ public static class WinixFontNative {
174
+ [DllImport("gdi32.dll", CharSet=CharSet.Unicode, SetLastError=true)]
175
+ public static extern int AddFontResourceEx(string path, uint flags, IntPtr reserved);
176
+ [DllImport("user32.dll", CharSet=CharSet.Unicode, SetLastError=true)]
177
+ public static extern IntPtr SendMessageTimeout(IntPtr hwnd, uint message, IntPtr wparam, IntPtr lparam, uint flags, uint timeout, out IntPtr result);
178
+ }
179
+ '@
180
+ }
181
+ New-Item -ItemType Directory -Path $destination -Force | Out-Null
182
+ $registry = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Software\Microsoft\Windows NT\CurrentVersion\Fonts')
183
+ try {
184
+ foreach ($font in $prepared.Values) {
185
+ if (-not (Test-Path -LiteralPath $font.path)) { [IO.File]::Copy($font.source, $font.path, $false) }
186
+ if ((Get-FileHash -LiteralPath $font.path -Algorithm SHA256).Hash -ne $font.sha256) { throw 'Font changed during installation' }
187
+ $registered = $registry.GetValue($font.name)
188
+ if ($null -ne $registered -and $registered -ne $font.path) { throw "Font registry changed during installation: $($font.name)" }
189
+ if ($null -eq $registered) {
190
+ if ([WinixFontNative]::AddFontResourceEx($font.path, 0, [IntPtr]::Zero) -eq 0) { throw "Windows rejected font: $($font.path)" }
191
+ $registry.SetValue($font.name, $font.path, [Microsoft.Win32.RegistryValueKind]::String)
192
+ }
193
+ Write-Host ("Installed font families: " + ($font.families -join ', '))
194
+ }
195
+ } finally { $registry.Dispose() }
196
+ $result = [IntPtr]::Zero
197
+ if ([WinixFontNative]::SendMessageTimeout([IntPtr]0xffff, 0x001d, [IntPtr]::Zero, [IntPtr]::Zero, 2, 5000, [ref]$result) -eq [IntPtr]::Zero) {
198
+ Write-Warning 'Font change notification timed out; applications may need restarting.'
199
+ }
200
+ $record = @{ version = 1; fonts = @($prepared.Values | ForEach-Object { @{ name = $_.name; path = $_.path; sha256 = $_.sha256; families = $_.families } }); sources = @($localSources.ToArray()) }
201
+ $pending = Join-Path $stage 'manifest.json'
202
+ $record | ConvertTo-Json -Depth 8 | Set-Content -LiteralPath $pending -Encoding utf8
203
+ [IO.File]::Move($pending, $manifest, $true)
204
+ } finally { Remove-Item -LiteralPath $stage -Recurse -Force }
205
+ }
206
+ `;
@@ -0,0 +1,32 @@
1
+ import type { EvaluatedHost } from "../../evaluator/index.js";
2
+ import type { WinFontSource, WinDscProperties } from "../../types/windows.js";
3
+ import type { WindowsLock } from "./lockfile.js";
4
+ export interface WindowsFontPin {
5
+ url: string;
6
+ sha256: string;
7
+ format: "zip" | "ttf" | "otf";
8
+ version?: string;
9
+ resolvedAt: string;
10
+ }
11
+ export type RemoteFontSource = Exclude<WinFontSource, string>;
12
+ export type WindowsFontResolver = (source: RemoteFontSource) => Promise<WindowsFontPin>;
13
+ export declare function fontSourceKey(source: RemoteFontSource): string;
14
+ export declare function validFontPin(value: unknown): value is WindowsFontPin;
15
+ export declare function fontPinMatches(source: RemoteFontSource, pin: WindowsFontPin): boolean;
16
+ export declare function fontFetch(url: string): Promise<Response>;
17
+ export interface NerdFontsCatalog {
18
+ version: string;
19
+ fonts: {
20
+ family: string;
21
+ url: string;
22
+ sha256?: string;
23
+ }[];
24
+ }
25
+ export declare function nerdFontsCatalog(version?: string): Promise<NerdFontsCatalog>;
26
+ export declare const resolveFontSource: WindowsFontResolver;
27
+ export declare function collectFontSources(hosts: EvaluatedHost[]): Map<string, RemoteFontSource>;
28
+ export declare function resolveWindowsFonts(lock: WindowsLock, sources: Iterable<RemoteFontSource>, resolver?: WindowsFontResolver, now?: Date, missingOnly?: boolean): Promise<{
29
+ lock: WindowsLock;
30
+ changed: boolean;
31
+ }>;
32
+ export declare function fontsProperties(sources: WinFontSource[], lock: WindowsLock, configDir?: string): WinDscProperties;
@@ -0,0 +1,199 @@
1
+ import { createHash } from "node:crypto";
2
+ import { fontHttpsUrl, validateFontSources } from "../../helpers/windows-personalization.js";
3
+ import { resolveWindowsSource } from "../../helpers/windows.js";
4
+ import { powerShellLiteral as quote } from "../../helpers/utils.js";
5
+ import { windowsSourcePath } from "./paths.js";
6
+ import { fontInstallPrelude } from "./fonts-runtime.js";
7
+ const maxDownloadBytes = 128 * 1024 * 1024;
8
+ export function fontSourceKey(source) {
9
+ validateFontSources([source]);
10
+ const identity = "provider" in source
11
+ ? { provider: source.provider, family: source.family, version: source.version ?? null }
12
+ : { url: fontHttpsUrl(source.url), sha256: source.sha256?.toLowerCase() ?? null, files: source.files ?? null };
13
+ return createHash("sha256").update(JSON.stringify(identity)).digest("hex");
14
+ }
15
+ export function validFontPin(value) {
16
+ if (!value || typeof value !== "object")
17
+ return false;
18
+ const pin = value;
19
+ if (typeof pin.url !== "string" || typeof pin.sha256 !== "string" ||
20
+ !/^[a-f0-9]{64}$/.test(pin.sha256) || !["zip", "ttf", "otf"].includes(String(pin.format)) ||
21
+ typeof pin.resolvedAt !== "string" ||
22
+ (pin.version !== undefined && (typeof pin.version !== "string" || !/^v\d+\.\d+\.\d+$/.test(pin.version))))
23
+ return false;
24
+ try {
25
+ return fontHttpsUrl(pin.url) === pin.url;
26
+ }
27
+ catch {
28
+ return false;
29
+ }
30
+ }
31
+ export function fontPinMatches(source, pin) {
32
+ if (!validFontPin(pin))
33
+ return false;
34
+ if ("url" in source)
35
+ return pin.url === fontHttpsUrl(source.url) &&
36
+ pin.format === new URL(source.url).pathname.split(".").at(-1)?.toLowerCase() &&
37
+ (source.sha256 === undefined || source.sha256.toLowerCase() === pin.sha256);
38
+ return pin.format === "zip" && pin.version !== undefined &&
39
+ (source.version === undefined || source.version === pin.version) &&
40
+ pin.url === `https://github.com/ryanoasis/nerd-fonts/releases/download/${pin.version}/${source.family}.zip`;
41
+ }
42
+ export async function fontFetch(url) {
43
+ let current = fontHttpsUrl(url);
44
+ for (let redirects = 0; redirects <= 5; redirects++) {
45
+ const response = await fetch(current, {
46
+ redirect: "manual", signal: AbortSignal.timeout(60000),
47
+ headers: { "User-Agent": "Winix-font-resolver", Accept: "application/json, application/octet-stream" },
48
+ });
49
+ if ([301, 302, 303, 307, 308].includes(response.status)) {
50
+ const location = response.headers.get("location");
51
+ await response.body?.cancel();
52
+ if (!location)
53
+ throw new Error("Font download redirect has no Location");
54
+ current = fontHttpsUrl(new URL(location, current).href);
55
+ continue;
56
+ }
57
+ if (!response.ok) {
58
+ await response.body?.cancel();
59
+ throw new Error(`Font request failed (${response.status}) for ${current}`);
60
+ }
61
+ return response;
62
+ }
63
+ throw new Error("Too many font download redirects");
64
+ }
65
+ async function fontResponseBytes(response, limit) {
66
+ const reader = response.body?.getReader();
67
+ if (!reader)
68
+ throw new Error("Empty font response");
69
+ const chunks = [];
70
+ let length = 0;
71
+ try {
72
+ while (true) {
73
+ const { value, done } = await reader.read();
74
+ if (done)
75
+ break;
76
+ length += value.length;
77
+ if (length > limit)
78
+ throw new Error("Font response exceeds the size limit");
79
+ chunks.push(value);
80
+ }
81
+ }
82
+ finally {
83
+ await reader.cancel();
84
+ }
85
+ return Buffer.concat(chunks);
86
+ }
87
+ export async function nerdFontsCatalog(version) {
88
+ if (version !== undefined && !/^v\d+\.\d+\.\d+$/.test(version))
89
+ throw new Error("Invalid Nerd Fonts release tag");
90
+ const response = await fontFetch(`https://api.github.com/repos/ryanoasis/nerd-fonts/releases/${version ? `tags/${version}` : "latest"}`);
91
+ const data = JSON.parse((await fontResponseBytes(response, 4 * 1024 * 1024)).toString("utf8"));
92
+ if (!data || typeof data !== "object")
93
+ throw new Error("Invalid Nerd Fonts release metadata");
94
+ const release = data;
95
+ if (typeof release.tag_name !== "string" || !/^v\d+\.\d+\.\d+$/.test(release.tag_name) ||
96
+ !Array.isArray(release.assets) || release.draft || release.prerelease ||
97
+ (version !== undefined && release.tag_name !== version))
98
+ throw new Error("Invalid Nerd Fonts release");
99
+ const fonts = [];
100
+ for (const asset of release.assets) {
101
+ if (!asset || typeof asset !== "object" || typeof asset.name !== "string" ||
102
+ !/^[a-z0-9][a-z0-9_-]*\.zip$/i.test(asset.name))
103
+ continue;
104
+ const family = asset.name.slice(0, -4);
105
+ const url = `https://github.com/ryanoasis/nerd-fonts/releases/download/${release.tag_name}/${asset.name}`;
106
+ if (asset.browser_download_url !== url)
107
+ throw new Error(`Unexpected Nerd Fonts download URL for ${family}`);
108
+ if (fonts.some((font) => font.family === family))
109
+ throw new Error(`Duplicate Nerd Fonts asset ${family}`);
110
+ fonts.push({ family, url, ...(typeof asset.digest === "string" && /^sha256:[a-f0-9]{64}$/.test(asset.digest)
111
+ ? { sha256: asset.digest.slice(7) } : {}) });
112
+ }
113
+ if (!fonts.length)
114
+ throw new Error("Nerd Fonts release has no font ZIP assets");
115
+ return { version: release.tag_name, fonts: fonts.sort((a, b) => a.family.localeCompare(b.family)) };
116
+ }
117
+ export const resolveFontSource = async (source) => {
118
+ validateFontSources([source]);
119
+ let url;
120
+ let sha256;
121
+ let version;
122
+ let format;
123
+ if ("provider" in source) {
124
+ const catalog = await nerdFontsCatalog(source.version);
125
+ const font = catalog.fonts.find((entry) => entry.family === source.family);
126
+ if (!font)
127
+ throw new Error(`Nerd Fonts ID "${source.family}" does not exist in ${catalog.version}. Run winix fonts search --provider nerd-fonts.`);
128
+ ({ url, sha256 } = font);
129
+ version = catalog.version;
130
+ format = "zip";
131
+ }
132
+ else {
133
+ url = fontHttpsUrl(source.url);
134
+ sha256 = source.sha256?.toLowerCase();
135
+ const extension = new URL(url).pathname.split(".").at(-1)?.toLowerCase();
136
+ if (extension !== "zip" && extension !== "ttf" && extension !== "otf")
137
+ throw new Error("Invalid font format");
138
+ format = extension;
139
+ }
140
+ if (!sha256) {
141
+ const bytes = await fontResponseBytes(await fontFetch(url), maxDownloadBytes);
142
+ sha256 = createHash("sha256").update(bytes).digest("hex");
143
+ }
144
+ return { url, sha256, format, ...(version ? { version } : {}), resolvedAt: new Date().toISOString() };
145
+ };
146
+ export function collectFontSources(hosts) {
147
+ const sources = new Map();
148
+ for (const host of hosts)
149
+ for (const resource of host.windows.dsc ?? []) {
150
+ if (resource.winix?.kind !== "fonts")
151
+ continue;
152
+ validateFontSources(resource.winix.sources);
153
+ for (const source of resource.winix.sources)
154
+ if (typeof source !== "string")
155
+ sources.set(fontSourceKey(source), source);
156
+ }
157
+ return sources;
158
+ }
159
+ export async function resolveWindowsFonts(lock, sources, resolver = resolveFontSource, now = new Date(), missingOnly = false) {
160
+ const fonts = { ...lock.fonts };
161
+ let changed = false;
162
+ for (const source of sources) {
163
+ const key = fontSourceKey(source);
164
+ if (fonts[key] && !fontPinMatches(source, fonts[key]))
165
+ throw new Error(`Font lock does not match declaration ${key}`);
166
+ if (missingOnly && fonts[key])
167
+ continue;
168
+ const pin = { ...await resolver(source), resolvedAt: now.toISOString() };
169
+ if (!fontPinMatches(source, pin))
170
+ throw new Error("Invalid font resolution");
171
+ const previous = fonts[key];
172
+ if (previous && previous.url === pin.url && previous.sha256 === pin.sha256 && previous.version === pin.version)
173
+ continue;
174
+ fonts[key] = pin;
175
+ changed = true;
176
+ }
177
+ return { lock: changed ? { ...lock, fonts, generatedAt: now.toISOString() } : lock, changed };
178
+ }
179
+ export function fontsProperties(sources, lock, configDir) {
180
+ validateFontSources(sources);
181
+ const plan = sources.map((source) => {
182
+ if (typeof source === "string")
183
+ return { path: resolveWindowsSource(source, configDir, windowsSourcePath) };
184
+ const pin = lock.fonts?.[fontSourceKey(source)];
185
+ if (!pin || !fontPinMatches(source, pin))
186
+ throw new Error("Font source has no matching pin; run winix update --windows fonts");
187
+ return { ...pin, files: "url" in source ? source.files ?? ["**/*.ttf", "**/*.otf"] : ["**/*.ttf", "**/*.otf"] };
188
+ });
189
+ const identity = createHash("sha256").update(JSON.stringify(plan)).digest("hex");
190
+ const prelude = `$ErrorActionPreference = 'Stop'
191
+ $plan = @(ConvertFrom-Json ${quote(JSON.stringify(plan))})
192
+ $manifest = Join-Path $env:LOCALAPPDATA 'Winix\\fonts\\${identity}.json'
193
+ ${fontInstallPrelude}`;
194
+ return {
195
+ getScript: `${prelude}\n@{ InDesiredState = (Test-WinixFonts) }`,
196
+ testScript: `${prelude}\nTest-WinixFonts`,
197
+ setScript: `${prelude}\nif (-not (Test-WinixFonts)) { Install-WinixFonts }\nif (-not (Test-WinixFonts)) { throw 'Font installation verification failed' }`,
198
+ };
199
+ }
@@ -35,6 +35,8 @@ import { powerShellRepositoryUri, resolvePowerShellModule, validateWindowsPowerS
35
35
  import { powerShellLiteral as psSingleQuoted } from "../../helpers/utils.js";
36
36
  import { windowsSourcePath } from "./paths.js";
37
37
  import { optionalFeatureProperties, wslDistroProperties } from "./wsl.js";
38
+ import { fontsProperties } from "./fonts.js";
39
+ import { wallpaperProperties } from "./personalization.js";
38
40
  export { isWindowsHost } from "./host.js";
39
41
  const DSC_SCHEMA = "https://raw.githubusercontent.com/PowerShell/DSC/main/schemas/2023/08/config/document.json";
40
42
  const WINGET_PACKAGE_TYPE = "Microsoft.WinGet/Package";
@@ -85,6 +87,12 @@ function generateConfiguration(hostName, win, lock, configDir) {
85
87
  .map((resource) => ({ kind: "dsc", token: resource.token }));
86
88
  const resources = (win.dsc ?? []).map((resource) => {
87
89
  const metadata = resource.winix;
90
+ if (metadata?.kind === "fonts") {
91
+ return cloneDscResource(resource, fontsProperties(metadata.sources, lock, configDir));
92
+ }
93
+ if (metadata?.kind === "wallpaper") {
94
+ return cloneDscResource(resource, wallpaperProperties(metadata.wallpaper, configDir));
95
+ }
88
96
  if (metadata?.kind === "file") {
89
97
  const properties = resolveWindowsFileProperties(resource, configDir, windowsSourcePath);
90
98
  if (metadata.wslConfig && properties) {
@@ -1,3 +1,4 @@
1
+ import { type WindowsFontPin } from "./fonts.js";
1
2
  import type { EvaluatedHost } from "../../evaluator/index.js";
2
3
  import type { WinPackage, WinPackageSource } from "../../types/index.js";
3
4
  import { type WslArchitecture, type WindowsWslImageResolver } from "./wsl.js";
@@ -14,6 +15,7 @@ export interface WindowsLock {
14
15
  version: typeof WINDOWS_LOCK_VERSION;
15
16
  generatedAt: string;
16
17
  packages: Record<string, WindowsLockPackage>;
18
+ fonts?: Record<string, WindowsFontPin>;
17
19
  /** Source-qualified lowercase keys; legacy name-only entries remain readable. */
18
20
  modules?: Record<string, WindowsLockModule>;
19
21
  wslImages?: Record<string, WindowsLockWslImage>;
@@ -1,4 +1,5 @@
1
1
  import { existsSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { validFontPin } from "./fonts.js";
2
3
  import { join } from "node:path";
3
4
  import { createHash } from "node:crypto";
4
5
  import { validWslImage } from "./wsl.js";
@@ -165,6 +166,11 @@ export function serializeWindowsLock(lock) {
165
166
  sorted.modules[name] = { ...lock.modules[name] };
166
167
  }
167
168
  }
169
+ if (lock.fonts !== undefined) {
170
+ sorted.fonts = {};
171
+ for (const key of Object.keys(lock.fonts).sort(comparePackageIds))
172
+ sorted.fonts[key] = { ...lock.fonts[key] };
173
+ }
168
174
  if (lock.wslImages !== undefined) {
169
175
  sorted.wslImages = {};
170
176
  for (const key of Object.keys(lock.wslImages).sort(comparePackageIds)) {
@@ -363,6 +369,16 @@ function validateWindowsLock(value) {
363
369
  }
364
370
  }
365
371
  const wslImages = {};
372
+ const fonts = {};
373
+ if (value.fonts !== undefined) {
374
+ if (!isObject(value.fonts))
375
+ throw new Error(`${WINDOWS_LOCKFILE_NAME} fonts must be an object`);
376
+ for (const [key, pin] of Object.entries(value.fonts)) {
377
+ if (!/^[a-f0-9]{64}$/.test(key) || !validFontPin(pin))
378
+ throw new Error(`${WINDOWS_LOCKFILE_NAME} font pin "${key}" is invalid`);
379
+ fonts[key] = { ...pin };
380
+ }
381
+ }
366
382
  if (value.wslImages !== undefined) {
367
383
  if (!isObject(value.wslImages))
368
384
  throw new Error(`${WINDOWS_LOCKFILE_NAME} wslImages must be an object.`);
@@ -388,6 +404,7 @@ function validateWindowsLock(value) {
388
404
  version: WINDOWS_LOCK_VERSION,
389
405
  generatedAt: value.generatedAt,
390
406
  packages,
407
+ ...(value.fonts === undefined ? {} : { fonts }),
391
408
  ...(value.modules === undefined ? {} : { modules }),
392
409
  ...(value.wslImages === undefined ? {} : { wslImages }),
393
410
  ...(value.wslRepositories === undefined ? {} : { wslRepositories }),
@@ -0,0 +1,4 @@
1
+ import type { WinDscProperties, WinWallpaper } from "../../types/windows.js";
2
+ import type { PersonalizationRegistryValue } from "../../helpers/windows-personalization.js";
3
+ export declare function personalizationProperties(values: PersonalizationRegistryValue[], autoHide?: boolean): WinDscProperties;
4
+ export declare function wallpaperProperties(wallpaper: WinWallpaper, configDir?: string): WinDscProperties;