@adrifer/winix 0.2.4-preview.2 → 0.3.0-preview.1

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
@@ -100,7 +100,8 @@ For what it's worth: Winix today works just as well on macOS and native NixOS as
100
100
  `winix-windows-x64.exe`, `winix-windows-arm64.exe`, `winix-linux-x64`,
101
101
  `winix-linux-arm64`, and `SHA256SUMS`. Choose a versioned release and the native
102
102
  architecture, compare its SHA256 with `SHA256SUMS`, and keep the executable
103
- outside the config checkout. Windows binaries are not yet code-signed:
103
+ outside tracked files (repository bootstrap uses the ignored `.winix` directory).
104
+ Windows binaries are not yet code-signed:
104
105
  checksums detect corruption, not publisher identity. Respect organizational
105
106
  execution/network policies; do not disable TLS verification.
106
107
  Redistribution notices and runtime source/rebuild references accompany the
@@ -144,6 +145,87 @@ must come from a complete official release; developer single-target builds
144
145
  lack the Linux checksums. ARM64 assets are cross-compiled; fresh-machine
145
146
  activation and ARM64 execution are not yet verified.
146
147
 
148
+ ### Bootstrap an existing repository
149
+
150
+ The Winix-owned `bootstrap-windows.ps1` and `bootstrap-linux.sh` release assets
151
+ prepare a trusted config repository without Node/npm. Download the script and
152
+ its `.sha256` from a **versioned release supporting repository bootstrap**,
153
+ verify the checksum, and review the script before running it. Do not pipe
154
+ unreviewed internet code into a shell. Checksums share the release's trust
155
+ boundary; they are not signatures.
156
+
157
+ ```powershell
158
+ .\bootstrap-windows.ps1 -Repository https://github.com/example/dotfiles.git `
159
+ -Ref main -Destination "$HOME\dotfiles" -ConfigDirectory winix `
160
+ -HostName windows-devbox -PrepareOnly
161
+ ```
162
+
163
+ ```bash
164
+ bash bootstrap-linux.sh --repository https://github.com/example/dotfiles.git \
165
+ --ref main --destination "$HOME/dotfiles" --config-directory winix \
166
+ --host linux-desktop --prepare-only
167
+ ```
168
+
169
+ Windows needs App Installer/WinGet initially. It ensures Git, makes a regular
170
+ clone, reads `config-directory/package.json` **without importing the config**,
171
+ then verifies and installs that exact release's native executable and
172
+ prerequisite-only script. Native PowerShell/DSC prerequisites are installed
173
+ without Node or PSGallery registration: feeds belong to the selected host.
174
+ Linux uses existing Nix to obtain temporary Git/Python tools, or requires
175
+ Git and Python 3 installed through your approved package manager. It does not
176
+ install Nix or turn another distribution into NixOS. Generic glibc Linux needs
177
+ libstdc++; NixOS gets a private, GC-rooted pinned libc/compiler launcher.
178
+ Real activation still requires the target's existing Nix/activation tools.
179
+
180
+ Pin `@adrifer/winix` in dependencies/devDependencies to an exact release version
181
+ or its matching official GitHub release SDK tarball URL. Floating ranges,
182
+ local SDK links, third-party URLs, and mismatched asset versions are refused.
183
+ `winix init` now generates an exact pin. No independent runtime version is
184
+ stored in dotfiles, and no global Winix/npm installation is performed.
185
+
186
+ `-DryRun` / `--dry-run` makes **no changes**, including no clone, tool downloads,
187
+ prerequisite installation, or config evaluation. `-PrepareOnly` / `--prepare-only`
188
+ allows those preparation steps, then runs `check` and `switch --dry` but stops
189
+ before activation. Config evaluation can itself run arbitrary code, so it
190
+ requires consent **before** `check`. Omit prepare-only to review the preview
191
+ and confirm activation separately. `-Yes` / `--yes` explicitly accepts trust,
192
+ prerequisite changes, activation (unless prepare-only), and managed removals.
193
+ Host selection does not rename the machine. Reboot/WSL shutdown are manual.
194
+
195
+ Existing checkouts must have the expected origin, local ref/HEAD and clean
196
+ working tree. Bootstrap never pulls, resets, stashes, changes branches in an
197
+ existing checkout, or overwrites an unrelated directory; links/path escapes
198
+ are rejected. Rerun after resolving a reported prerequisite/reboot boundary.
199
+ Updating an existing checkout is an explicit Git operation, not a bootstrap side effect.
200
+
201
+ For ongoing use, bootstrap writes `.winix/bin/winix.ps1` (Windows) or
202
+ `.winix/bin/winix` (Linux). These call `winix run <args>` from the config directory:
203
+
204
+ ```powershell
205
+ .\.winix\bin\winix.ps1 check
206
+ .\.winix\bin\winix.ps1 switch --host windows-devbox
207
+ ```
208
+
209
+ ```bash
210
+ ./.winix/bin/winix check
211
+ ./.winix/bin/winix switch --host linux-desktop
212
+ ```
213
+
214
+ The launcher rereads the manifest on every invocation. If an optional
215
+ `node_modules/@adrifer/winix` is installed, its version must match the pin and
216
+ the launcher uses its own CLI/SDK under Node >=22.13. Install dependencies
217
+ explicitly with `npm ci` using an approved npm source; bootstrap never does it.
218
+ Existing `npm run` scripts also use that local CLI, without a global installation.
219
+ Without the npm SDK, the verified standalone executable must match the pin;
220
+ after changing the pin, rerun bootstrap to download the matching executable.
221
+ A stale/corrupt local installation is an error, never a silent standalone fallback.
222
+
223
+ Fresh Windows-driven WSL setups using a branch now fetch full history and
224
+ create a local tracking branch **at the locked first-run commit**, even if
225
+ upstream has advanced. `HEAD` resolves the default branch; commit/tag refs stay
226
+ detached intentionally. Completed setups and their existing detached checkouts
227
+ are not migrated or updated automatically.
228
+
147
229
  ### npm installation (optional)
148
230
 
149
231
  ```bash
@@ -536,7 +618,8 @@ other Linux/macOS systems does not translate local paths; use Windows-reachable
536
618
  absolute or environment-variable sources when generating there.
537
619
 
538
620
  PowerShell module versions and repositories are pinned in the optional `modules`
539
- section of the existing `winix-windows.lock` (lowercase module-name keys).
621
+ section of the existing `winix-windows.lock` (source-qualified lowercase keys;
622
+ legacy name-only pins remain readable).
540
623
  Old package-only locks remain valid. First apply resolves missing entries;
541
624
  subsequent applies reuse pins without querying the repository.
542
625
  `winix update --windows` refreshes packages and modules, or pass names to update
@@ -544,7 +627,7 @@ only selected entries; `--dry` resolves without writing. Resolution errors never
544
627
  replace existing pins. Network access is still needed for installation.
545
628
 
546
629
  `windows.powershell.module(name, { repository?, dependsOn? })` defaults to
547
- PSGallery, selects stable releases, and installs the exact locked version for
630
+ the host repository policy, otherwise PSGallery, selects stable releases, and installs the exact locked version for
548
631
  the current user. PowerShell 7 with PSResourceGet must already be available for
549
632
  resolution. Installation is idempotent and runs directly in DSC's
550
633
  `Microsoft.DSC.Transitional/PowerShellScript` resource; a declared `Microsoft.PowerShell` package is an
@@ -552,6 +635,41 @@ automatic dependency. Other versions are not removed. Profiles still import
552
635
  modules themselves; an unversioned `Import-Module` can load a newer installed
553
636
  version, so installation locking alone does not enforce session imports.
554
637
 
638
+ Work profiles can enforce an approved feed without changing shared features:
639
+
640
+ ```ts
641
+ const workRepositories = feature("work-repositories", ({ windows }) => {
642
+ windows.powershell.repositories({
643
+ repositories: {
644
+ approved: { uri: "https://packages.example.com/powershell/v3/index.json" },
645
+ },
646
+ default: "approved",
647
+ allowed: ["approved"],
648
+ });
649
+ });
650
+ const work = profile("work", [workRepositories(), windowsShell()]);
651
+ ```
652
+
653
+ The policy is resolved after host fragments merge. Omitted module repositories
654
+ and the automatic `Microsoft.Windows.Settings` installer use its default.
655
+ Explicit repositories outside `allowed` fail before resolution; there is no
656
+ fallback. Omit `allowed` to permit explicit overrides. It governs Winix-managed
657
+ PowerShell installers, not raw commands, generic DSC, npm, NuGet, or WSL.
658
+ Personal hosts without this feature retain PSGallery.
659
+ Conflicting policies in one host fail instead of silently widening its allowlist.
660
+
661
+ Named feeds use HTTPS URLs without embedded credentials. Version resolution
662
+ registers a missing feed for the current user; activation also ensures registration
663
+ before module installation. A same-name registration with a different URI is an
664
+ error, never overwritten. Registration persists, but global priorities and permanent
665
+ trust are unchanged. Authenticate separately using the organization's supported
666
+ PSResourceGet setup; do not put secrets in config or locks. `--dry` does not write
667
+ the lock or activate resources, but resolving missing versions can register a feed.
668
+ Pins distinguish module name, repository name, and configured URI across hosts;
669
+ a new source resolves its own pin. Existing matching installed versions are reused,
670
+ not reinstalled to attest their original source. Settings retains its existing
671
+ prerelease ensure behavior rather than adding a stable module lock.
672
+
555
673
  ### Provision WSL from a Windows host
556
674
 
557
675
  ```ts
@@ -27,10 +27,11 @@
27
27
  // processor is selected by the metadata block.
28
28
  import { win32 } from "node:path";
29
29
  import { yamlEntry, yamlScalar } from "./yaml.js";
30
- import { emptyWindowsLock, reconcileInlinePins, } from "./lockfile.js";
30
+ import { emptyWindowsLock, reconcileInlinePins, windowsModulePin, } from "./lockfile.js";
31
31
  import { isWindowsHost } from "./host.js";
32
32
  import { resolveWindowsFileProperties } from "../../helpers/windows.js";
33
- import { powerShellModuleProperties } from "./powershell.js";
33
+ import { powerShellModuleProperties, powerShellRepositoryScripts } from "./powershell.js";
34
+ import { powerShellRepositoryUri, resolvePowerShellModule, validateWindowsPowerShellPolicy } from "../../helpers/windows-repositories.js";
34
35
  import { powerShellLiteral as psSingleQuoted } from "../../helpers/utils.js";
35
36
  import { windowsSourcePath } from "./paths.js";
36
37
  import { optionalFeatureProperties, wslDistroProperties } from "./wsl.js";
@@ -62,7 +63,23 @@ export function generateWindows(evaluatedHosts, lock = emptyWindowsLock(), confi
62
63
  */
63
64
  function generateConfiguration(hostName, win, lock, configDir) {
64
65
  validateWindowsWslResources(win);
66
+ validateWindowsPowerShellPolicy(win);
65
67
  const packages = sortedPackages(win.packages ?? {});
68
+ const registrations = Object.entries(win.powershell?.repositories?.repositories ?? {}).map(([name, feed]) => {
69
+ const scripts = powerShellRepositoryScripts(name, powerShellRepositoryUri(feed.uri));
70
+ const resource = {
71
+ name: `Register PowerShell repository ${name}`,
72
+ resourceType: "Microsoft.DSC.Transitional/PowerShellScript",
73
+ properties: { getScript: scripts.get, testScript: scripts.test, setScript: scripts.set },
74
+ dependsOn: packages.filter((pkg) => pkg.id.toLowerCase() === "microsoft.powershell")
75
+ .map((pkg) => ({ kind: "package", id: pkg.id })),
76
+ };
77
+ Object.defineProperty(resource, "token", { value: Symbol(name), enumerable: false });
78
+ return { name, resource };
79
+ });
80
+ const repositoryDependencies = (repository) => registrations
81
+ .filter((entry) => entry.name.toLowerCase() === repository.toLowerCase())
82
+ .map((entry) => ({ kind: "dsc", token: entry.resource.token }));
66
83
  const resources = (win.dsc ?? []).map((resource) => {
67
84
  const metadata = resource.winix;
68
85
  if (metadata?.kind === "file") {
@@ -87,12 +104,12 @@ function generateConfiguration(hostName, win, lock, configDir) {
87
104
  ]);
88
105
  }
89
106
  if (metadata?.kind === "powershell-module") {
90
- const module = metadata.module;
91
- const pin = lock.modules?.[module.name.toLowerCase()];
92
- if (!pin || pin.repository.toLowerCase() !== module.repository.toLowerCase()) {
107
+ const module = resolvePowerShellModule(win, metadata.module);
108
+ const pin = windowsModulePin(lock, module);
109
+ if (!pin) {
93
110
  throw new Error(`PowerShell module "${module.name}" has no matching pin in winix-windows.lock. Run winix update --windows.`);
94
111
  }
95
- const dependencies = [...(resource.dependsOn ?? [])];
112
+ const dependencies = [...repositoryDependencies(module.repository), ...(resource.dependsOn ?? [])];
96
113
  if (packages.some((pkg) => pkg.id === "Microsoft.PowerShell") &&
97
114
  !dependencies.some((ref) => ref.kind === "package" && ref.id === "Microsoft.PowerShell")) {
98
115
  dependencies.push({ kind: "package", id: "Microsoft.PowerShell" });
@@ -101,9 +118,10 @@ function generateConfiguration(hostName, win, lock, configDir) {
101
118
  }
102
119
  return resource;
103
120
  });
104
- const prepared = prepareWindowsDscResources(win.commands ?? [], resources);
121
+ const settingsModule = resolvePowerShellModule(win, { name: "Microsoft.Windows.Settings" });
122
+ const prepared = prepareWindowsDscResources(win.commands ?? [], resources, settingsModule.repository, repositoryDependencies(settingsModule.repository));
105
123
  const commands = prepared.commands;
106
- const dscResources = prepared.dscResources;
124
+ const dscResources = [...registrations.map((entry) => entry.resource), ...prepared.dscResources];
107
125
  const lines = [];
108
126
  lines.push(`# yaml-language-server: $schema=${DSC_SCHEMA}`);
109
127
  lines.push(`# Generated by Winix for host "${hostName}". Do not edit.`);
@@ -184,12 +202,12 @@ export function validateWindowsWslResources(win) {
184
202
  throw new Error('WSL distro provisioning requires windows.package("Microsoft.WSL")');
185
203
  }
186
204
  }
187
- function prepareWindowsDscResources(commands, resources) {
205
+ function prepareWindowsDscResources(commands, resources, settingsRepository, repositoryDependencies) {
188
206
  const envResolvedResources = resolveManagedEnvironmentReferences(resources);
189
207
  if (!envResolvedResources.some((resource) => resource.winix?.kind === "setting")) {
190
208
  return { commands: [...commands], dscResources: envResolvedResources };
191
209
  }
192
- const ensureModule = createWindowsSettingsEnsureCommand();
210
+ const ensureModule = createWindowsSettingsEnsureCommand(settingsRepository, repositoryDependencies);
193
211
  const ensureRef = { kind: "dsc", token: ensureModule.token };
194
212
  return {
195
213
  commands: [...commands],
@@ -206,7 +224,7 @@ function prepareWindowsDscResources(commands, resources) {
206
224
  ],
207
225
  };
208
226
  }
209
- function createWindowsSettingsEnsureCommand() {
227
+ function createWindowsSettingsEnsureCommand(repository, dependsOn) {
210
228
  // Microsoft.Windows.Settings currently publishes the WindowsSettings resource
211
229
  // as a prerelease module (the upstream sample uses v0.1.0-alpha), so the
212
230
  // ensure step must opt into prerelease discovery for now. Revisit/remove
@@ -214,6 +232,7 @@ function createWindowsSettingsEnsureCommand() {
214
232
  const resource = {
215
233
  name: WINDOWS_SETTINGS_MODULE_COMMAND_NAME,
216
234
  resourceType: RUN_COMMAND_ON_SET_TYPE,
235
+ dependsOn,
217
236
  properties: {
218
237
  executable: "pwsh",
219
238
  arguments: {
@@ -223,7 +242,8 @@ function createWindowsSettingsEnsureCommand() {
223
242
  "3": [
224
243
  "$ErrorActionPreference = 'Stop';",
225
244
  "if (-not (Get-Module -ListAvailable -Name Microsoft.Windows.Settings)) {",
226
- " Install-PSResource -Name Microsoft.Windows.Settings -Prerelease -TrustRepository -AcceptLicense | Out-Null",
245
+ ` Install-PSResource -Name Microsoft.Windows.Settings -Repository ${psSingleQuoted(repository)} -Scope CurrentUser -Prerelease -TrustRepository -AcceptLicense -ErrorAction Stop | Out-Null;`,
246
+ " if (-not (Get-Module -ListAvailable -Name Microsoft.Windows.Settings)) { throw 'Microsoft.Windows.Settings was not installed' }",
227
247
  "}",
228
248
  ].join(" "),
229
249
  treatAsArray: true,
@@ -1,7 +1,8 @@
1
1
  import type { EvaluatedHost } from "../../evaluator/index.js";
2
- import type { WinPackage, WinPackageSource, WinPowerShellModule } from "../../types/index.js";
2
+ import type { WinPackage, WinPackageSource } from "../../types/index.js";
3
3
  import { type WslArchitecture, type WindowsWslImageResolver } from "./wsl.js";
4
4
  import { type WindowsLockWslRepository, type WindowsWslRepositoryResolver } from "./wsl-setup.js";
5
+ import { type ResolvedPowerShellModule } from "../../helpers/windows-repositories.js";
5
6
  export declare const WINDOWS_LOCKFILE_NAME = "winix-windows.lock";
6
7
  export declare const WINDOWS_LOCK_VERSION = 1;
7
8
  export interface WindowsLockPackage {
@@ -13,7 +14,7 @@ export interface WindowsLock {
13
14
  version: typeof WINDOWS_LOCK_VERSION;
14
15
  generatedAt: string;
15
16
  packages: Record<string, WindowsLockPackage>;
16
- /** PowerShell module names are case-insensitive, stored as lowercase keys. */
17
+ /** Source-qualified lowercase keys; legacy name-only entries remain readable. */
17
18
  modules?: Record<string, WindowsLockModule>;
18
19
  wslImages?: Record<string, WindowsLockWslImage>;
19
20
  wslRepositories?: Record<string, WindowsLockWslRepository>;
@@ -28,10 +29,13 @@ export interface WindowsLockWslImage {
28
29
  }
29
30
  export interface WindowsLockModule {
30
31
  repository: string;
32
+ repositoryUri?: string;
31
33
  version: string;
32
34
  resolvedAt: string;
33
35
  }
34
- export type WindowsModuleVersionResolver = (name: string, repository: string) => string;
36
+ export type WindowsModuleVersionResolver = (name: string, repository: string, repositoryUri?: string) => string;
37
+ export declare function windowsModuleKey(module: ResolvedPowerShellModule): string;
38
+ export declare function windowsModulePin(lock: WindowsLock, module: ResolvedPowerShellModule): WindowsLockModule | undefined;
35
39
  export type WindowsPackageVersionResolver = (id: string, source: WinPackageSource) => string;
36
40
  export interface WindowsLockResolution {
37
41
  id: string;
@@ -53,7 +57,7 @@ export declare function resolveMissingWindowsLockEntries(lock: WindowsLock, eval
53
57
  export declare function resolveWindowsLockEntries(lock: WindowsLock, packages: Iterable<WinPackage>, resolveVersion: WindowsPackageVersionResolver, now?: Date): WindowsLockResolutionResult;
54
58
  export declare function windowsLockChanged(before: WindowsLock, after: WindowsLock): boolean;
55
59
  export declare function serializeWindowsLock(lock: WindowsLock): string;
56
- export declare function collectWindowsModules(hosts: EvaluatedHost[]): Map<string, WinPowerShellModule>;
60
+ export declare function collectWindowsModules(hosts: EvaluatedHost[]): Map<string, ResolvedPowerShellModule>;
57
61
  export declare function hasWindowsWslDistros(hosts: EvaluatedHost[]): boolean;
58
62
  export declare function resolveWindowsWslImages(lock: WindowsLock, resolve: WindowsWslImageResolver, now?: Date, missingOnly?: boolean): {
59
63
  lock: WindowsLock;
@@ -63,7 +67,7 @@ export declare function resolveWindowsWslRepositories(lock: WindowsLock, hosts:
63
67
  lock: WindowsLock;
64
68
  changed: boolean;
65
69
  };
66
- export declare function resolveWindowsModuleLockEntries(lock: WindowsLock, modules: Iterable<WinPowerShellModule>, resolveVersion: WindowsModuleVersionResolver, now?: Date, missingOnly?: boolean): {
70
+ export declare function resolveWindowsModuleLockEntries(lock: WindowsLock, modules: Iterable<ResolvedPowerShellModule>, resolveVersion: WindowsModuleVersionResolver, now?: Date, missingOnly?: boolean): {
67
71
  lock: WindowsLock;
68
72
  resolutions: Omit<WindowsLockResolution, "source">[];
69
73
  changed: boolean;
@@ -1,9 +1,28 @@
1
1
  import { existsSync, readFileSync, writeFileSync } from "node:fs";
2
2
  import { join } from "node:path";
3
+ import { createHash } from "node:crypto";
3
4
  import { validWslImage } from "./wsl.js";
4
5
  import { validWslRepository, wslRepositoryKey, } from "./wsl-setup.js";
6
+ import { resolvePowerShellModule, powerShellRepositoryUri, } from "../../helpers/windows-repositories.js";
5
7
  export const WINDOWS_LOCKFILE_NAME = "winix-windows.lock";
6
8
  export const WINDOWS_LOCK_VERSION = 1;
9
+ export function windowsModuleKey(module) {
10
+ const name = module.name.toLowerCase();
11
+ if (!module.repositoryUri && module.repository.toLowerCase() === "psgallery")
12
+ return name;
13
+ const source = `${name}@${module.repository.toLowerCase()}`;
14
+ return module.repositoryUri
15
+ ? `${source}/${createHash("sha256").update(powerShellRepositoryUri(module.repositoryUri)).digest("hex")}`
16
+ : source;
17
+ }
18
+ export function windowsModulePin(lock, module) {
19
+ const pin = lock.modules?.[windowsModuleKey(module)] ??
20
+ (!module.repositoryUri ? lock.modules?.[module.name.toLowerCase()] : undefined);
21
+ if (pin?.repository.toLowerCase() !== module.repository.toLowerCase() ||
22
+ pin?.repositoryUri !== module.repositoryUri)
23
+ return undefined;
24
+ return pin;
25
+ }
7
26
  export function readWindowsLock(configDir) {
8
27
  const path = windowsLockPath(configDir);
9
28
  if (!existsSync(path))
@@ -162,15 +181,18 @@ export function serializeWindowsLock(lock) {
162
181
  export function collectWindowsModules(hosts) {
163
182
  const modules = new Map();
164
183
  for (const host of hosts) {
165
- for (const resource of host.windows.dsc ?? []) {
184
+ const win = host.windows;
185
+ const hostModules = new Map();
186
+ for (const resource of win.dsc ?? []) {
166
187
  if (resource.winix?.kind !== "powershell-module")
167
188
  continue;
168
- const module = resource.winix.module;
169
- const key = module.name.toLowerCase();
170
- const existing = modules.get(key);
171
- if (existing && existing.repository.toLowerCase() !== module.repository.toLowerCase()) {
189
+ const module = resolvePowerShellModule(win, resource.winix.module);
190
+ const key = windowsModuleKey(module);
191
+ const existing = hostModules.get(module.name.toLowerCase());
192
+ if (existing && existing !== key) {
172
193
  throw new Error(`PowerShell module "${module.name}" is declared with conflicting repositories.`);
173
194
  }
195
+ hostModules.set(module.name.toLowerCase(), key);
174
196
  modules.set(key, module);
175
197
  }
176
198
  }
@@ -235,17 +257,12 @@ export function resolveWindowsModuleLockEntries(lock, modules, resolveVersion, n
235
257
  const resolutions = [];
236
258
  let changed = false;
237
259
  for (const module of modules) {
238
- const key = module.name.toLowerCase();
239
- const previous = next.modules[key];
240
- if (previous && previous.repository.toLowerCase() !== module.repository.toLowerCase()) {
241
- if (missingOnly) {
242
- throw new Error(`PowerShell module "${module.name}" changed repository. Run winix update --windows ${module.name}.`);
243
- }
244
- }
245
- else if (missingOnly && previous) {
260
+ const key = windowsModuleKey(module);
261
+ const previous = windowsModulePin(next, module);
262
+ if (missingOnly && previous) {
246
263
  continue;
247
264
  }
248
- const version = resolveVersion(module.name, module.repository);
265
+ const version = resolveVersion(module.name, module.repository, module.repositoryUri);
249
266
  if (!/^\d+\.\d+\.\d+(?:\.\d+)?$/.test(version)) {
250
267
  throw new Error(`PowerShell module "${module.name}" resolver did not return a stable version: ${version}`);
251
268
  }
@@ -257,7 +274,11 @@ export function resolveWindowsModuleLockEntries(lock, modules, resolveVersion, n
257
274
  });
258
275
  if (unchanged)
259
276
  continue;
260
- next.modules[key] = { repository: module.repository, version, resolvedAt: now.toISOString() };
277
+ next.modules[key] = {
278
+ repository: module.repository,
279
+ ...(module.repositoryUri ? { repositoryUri: module.repositoryUri } : {}),
280
+ version, resolvedAt: now.toISOString(),
281
+ };
261
282
  next.generatedAt = now.toISOString();
262
283
  changed = true;
263
284
  }
@@ -312,16 +333,31 @@ function validateWindowsLock(value) {
312
333
  if (!isObject(value.modules))
313
334
  throw new Error(`${WINDOWS_LOCKFILE_NAME} modules must be an object.`);
314
335
  for (const [name, entry] of Object.entries(value.modules)) {
315
- if (!/^[a-z0-9][a-z0-9._-]*$/i.test(name) || !isObject(entry) ||
336
+ if (!/^[a-z0-9][a-z0-9._-]*(?:@[a-z0-9][a-z0-9._-]*(?:\/[a-f0-9]{64})?)?$/i.test(name) || !isObject(entry) ||
316
337
  typeof entry.repository !== "string" || !/^[a-z0-9][a-z0-9._-]*$/i.test(entry.repository) ||
317
338
  typeof entry.version !== "string" || !/^\d+\.\d+\.\d+(?:\.\d+)?$/.test(entry.version) ||
318
339
  typeof entry.resolvedAt !== "string") {
319
340
  throw new Error(`${WINDOWS_LOCKFILE_NAME} module "${name}" has an invalid repository, stable version, or resolvedAt.`);
320
341
  }
342
+ if (entry.repositoryUri !== undefined &&
343
+ (typeof entry.repositoryUri !== "string" || powerShellRepositoryUri(entry.repositoryUri) !== entry.repositoryUri)) {
344
+ throw new Error(`${WINDOWS_LOCKFILE_NAME} module "${name}" has an invalid repository URI.`);
345
+ }
321
346
  const key = name.toLowerCase();
347
+ if ((key.includes("@") || entry.repositoryUri !== undefined) &&
348
+ key !== windowsModuleKey({
349
+ name: name.split("@")[0], repository: entry.repository,
350
+ ...(typeof entry.repositoryUri === "string" ? { repositoryUri: entry.repositoryUri } : {}),
351
+ })) {
352
+ throw new Error(`${WINDOWS_LOCKFILE_NAME} module "${name}" does not match its repository identity.`);
353
+ }
322
354
  if (modules[key])
323
355
  throw new Error(`${WINDOWS_LOCKFILE_NAME} has duplicate module "${name}".`);
324
- modules[key] = { repository: entry.repository, version: entry.version, resolvedAt: entry.resolvedAt };
356
+ modules[key] = {
357
+ repository: entry.repository,
358
+ ...(typeof entry.repositoryUri === "string" ? { repositoryUri: entry.repositoryUri } : {}),
359
+ version: entry.version, resolvedAt: entry.resolvedAt,
360
+ };
325
361
  }
326
362
  }
327
363
  const wslImages = {};
@@ -1,6 +1,11 @@
1
1
  import type { WinDscProperties, WinPowerShellModule } from "../../types/index.js";
2
2
  import type { WindowsLockModule } from "./lockfile.js";
3
+ export declare function powerShellRepositoryScripts(name: string, uri: string): {
4
+ get: string;
5
+ test: string;
6
+ set: string;
7
+ };
3
8
  export type PowerShellGalleryRunner = (script: string) => string;
4
9
  /** Find-PSResource returns the newest stable release unless -Prerelease is requested. */
5
- export declare function resolvePowerShellModuleVersion(name: string, repository: string, run?: PowerShellGalleryRunner): string;
10
+ export declare function resolvePowerShellModuleVersion(name: string, repository: string, repositoryUriOrRunner?: string | PowerShellGalleryRunner, runner?: PowerShellGalleryRunner): string;
6
11
  export declare function powerShellModuleProperties(module: WinPowerShellModule, pin: WindowsLockModule): WinDscProperties;
@@ -1,9 +1,30 @@
1
1
  import { execFileSync } from "node:child_process";
2
2
  import { powerShellLiteral } from "../../helpers/utils.js";
3
+ export function powerShellRepositoryScripts(name, uri) {
4
+ const prelude = [
5
+ "$ErrorActionPreference = 'Stop'",
6
+ `$repositoryName = ${powerShellLiteral(name)}`,
7
+ `$repositoryUri = ${powerShellLiteral(uri)}`,
8
+ "$registeredRepository = @(Get-PSResourceRepository -ErrorAction Stop | Where-Object { $_.Name -ieq $repositoryName })",
9
+ `if ($registeredRepository.Count -gt 0 -and $registeredRepository[0].Uri.AbsoluteUri.TrimEnd('/') -cne $repositoryUri) { throw "PowerShell repository $repositoryName is already registered with a different URI; resolve the registration conflict explicitly" }`,
10
+ ];
11
+ return {
12
+ get: [...prelude, "$registeredRepository | Select-Object Name,Uri"].join("\n"),
13
+ test: [...prelude, "$registeredRepository.Count -eq 1"].join("\n"),
14
+ set: [
15
+ ...prelude,
16
+ "if ($registeredRepository.Count -eq 0) { Register-PSResourceRepository -Name $repositoryName -Uri $repositoryUri -ErrorAction Stop }",
17
+ ].join("\n"),
18
+ };
19
+ }
3
20
  /** Find-PSResource returns the newest stable release unless -Prerelease is requested. */
4
- export function resolvePowerShellModuleVersion(name, repository, run = (script) => execFileSync("pwsh", ["-NoLogo", "-NoProfile", "-NonInteractive", "-EncodedCommand", encode(script)], { encoding: "utf8" })) {
21
+ export function resolvePowerShellModuleVersion(name, repository, repositoryUriOrRunner, runner) {
22
+ const repositoryUri = typeof repositoryUriOrRunner === "string" ? repositoryUriOrRunner : undefined;
23
+ const run = (typeof repositoryUriOrRunner === "function" ? repositoryUriOrRunner : runner) ??
24
+ ((script) => execFileSync("pwsh", ["-NoLogo", "-NoProfile", "-NonInteractive", "-EncodedCommand", encode(script)], { encoding: "utf8" }));
5
25
  const script = [
6
26
  "$ErrorActionPreference = 'Stop'",
27
+ ...(repositoryUri ? [powerShellRepositoryScripts(repository, repositoryUri).set] : []),
7
28
  `$found = @(Find-PSResource -Name ${powerShellLiteral(name)} -Repository ${powerShellLiteral(repository)} -ErrorAction Stop)`,
8
29
  `if ($found.Count -ne 1 -or $found[0].Name -ine ${powerShellLiteral(name)} -or $found[0].Prerelease) { throw 'Expected one stable module release' }`,
9
30
  "$found[0].Version.ToString() | ConvertTo-Json -Compress",
@@ -18,6 +18,7 @@ interface CommandOptions {
18
18
  env?: NodeJS.ProcessEnv;
19
19
  }
20
20
  export type SetupRunner = (command: string, args: string[], options?: CommandOptions) => string;
21
+ export declare function checkoutWslRevision(git: (args: string[]) => string, ref: string, revision: string, existingHead?: string): void;
21
22
  export declare function createWslAccountPlan(host: EvaluatedHost, setup: WinWslSetup, architecture: string): {
22
23
  plan: Plan;
23
24
  accountHost: EvaluatedHost;
@@ -11,6 +11,51 @@ import { randomUUID } from "node:crypto";
11
11
  import * as fs from "node:fs/promises";
12
12
  import { join, resolve, dirname, relative, isAbsolute } from "node:path";
13
13
  import { pathToFileURL } from "node:url";
14
+ export function checkoutWslRevision(git, ref, revision, existingHead) {
15
+ git(["config", "remote.origin.fetch", "+refs/heads/*:refs/remotes/origin/*"]);
16
+ git(["fetch", "--no-tags", "origin"]);
17
+ git(["fetch", "--no-tags", "origin", revision]);
18
+ let branch;
19
+ if (ref === "HEAD") {
20
+ const remoteHead = git(["ls-remote", "--symref", "origin", "HEAD"]);
21
+ branch = /^ref: refs\/heads\/([^\s]+)\s+HEAD$/m.exec(remoteHead)?.[1];
22
+ if (!branch)
23
+ throw new Error("Cannot determine the repository default branch; use an explicit branch or commit");
24
+ }
25
+ else if (!ref.startsWith("refs/tags/") && !/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(ref)) {
26
+ const candidate = ref.replace(/^refs\/heads\//, "");
27
+ let isBranch = true;
28
+ try {
29
+ git(["show-ref", "--verify", "--quiet", `refs/remotes/origin/${candidate}`]);
30
+ }
31
+ catch (error) {
32
+ if (error.status !== 1)
33
+ throw error;
34
+ isBranch = false;
35
+ }
36
+ if (isBranch)
37
+ branch = candidate;
38
+ }
39
+ if (branch) {
40
+ git(["check-ref-format", "--branch", branch]);
41
+ let current;
42
+ try {
43
+ current = git(["symbolic-ref", "--quiet", "--short", "HEAD"]);
44
+ }
45
+ catch (error) {
46
+ if (error.status !== 1)
47
+ throw error;
48
+ }
49
+ if (!existingHead || current !== branch) {
50
+ // An unborn HEAD may already name this branch, but still needs its locked tree.
51
+ git(["checkout", existingHead ? "-b" : "-B", branch, revision]);
52
+ }
53
+ git(["branch", "--set-upstream-to", `origin/${branch}`, branch]);
54
+ }
55
+ else {
56
+ git(["checkout", "--detach", revision]);
57
+ }
58
+ }
14
59
  function object(value) {
15
60
  return value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
16
61
  }
@@ -270,8 +315,7 @@ export async function runWslSetup(request, options = {}) {
270
315
  }
271
316
  if (existingHead && existingHead !== state.revision)
272
317
  throw new Error("Staging revision changed; refusing reset");
273
- git(["fetch", "--depth=1", "--no-tags", "origin", state.revision]);
274
- git(["checkout", "--detach", state.revision]);
318
+ checkoutWslRevision(git, request.setup.ref ?? "HEAD", state.revision, existingHead);
275
319
  verify(repository, "nixos", initial.home);
276
320
  const config = await fs.realpath(join(repository, request.setup.configDirectory));
277
321
  const inside = relative(await fs.realpath(repository), config);
@@ -0,0 +1,15 @@
1
+ import { runCommand } from "../run.js";
2
+ export declare function pinnedWinixVersion(spec: unknown): string;
3
+ export declare function checkoutWinixVersion(directory: string): Promise<string>;
4
+ export declare function localWinixCommand(directory: string, expected: string, runtimeVersion: string, executable: string): Promise<{
5
+ command: string;
6
+ args: string[];
7
+ }>;
8
+ export declare function runCheckout(directory: string, args: string[], run?: typeof runCommand): Promise<void>;
9
+ export declare function nodeTypeArguments(version: string): string[];
10
+ export declare function bootstrapCheckout(directory: string, opts: {
11
+ host: string;
12
+ yes: boolean;
13
+ prepareOnly: boolean;
14
+ dry: boolean;
15
+ }, run?: typeof runCheckout): Promise<void>;