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

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
@@ -147,6 +147,12 @@ activation and ARM64 execution are not yet verified.
147
147
 
148
148
  ### Bootstrap an existing repository
149
149
 
150
+ Repository-specific entry scripts can download/verify Winix bootstrap installers and supply
151
+ repository, ref, destination, config-directory and host defaults. Git installation,
152
+ cloning and existing-checkout validation remain owned by Winix. Private HTTPS
153
+ repositories use Git's configured authentication/credential helper; never embed
154
+ credentials in scripts or repository URLs.
155
+
150
156
  The Winix-owned `bootstrap-windows.ps1` and `bootstrap-linux.sh` release assets
151
157
  prepare a trusted config repository without Node/npm. Download the script and
152
158
  its `.sha256` from a **versioned release supporting repository bootstrap**,
@@ -213,7 +219,7 @@ For ongoing use, bootstrap writes `.winix/bin/winix.ps1` (Windows) or
213
219
 
214
220
  The launcher rereads the manifest on every invocation. If an optional
215
221
  `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
222
+ the launcher uses its own CLI/SDK under supported Node 22.13+, 24 or 26. Install dependencies
217
223
  explicitly with `npm ci` using an approved npm source; bootstrap never does it.
218
224
  Existing `npm run` scripts also use that local CLI, without a global installation.
219
225
  Without the npm SDK, the verified standalone executable must match the pin;
@@ -235,8 +241,12 @@ npx @adrifer/winix@latest init
235
241
  npm install
236
242
  ```
237
243
 
238
- The npm CLI requires Node.js with native TypeScript transformation and the
239
- `--experimental-transform-types` flag (Node 22.13+ or 24; use Node 24).
244
+ The npm CLI supports stable Node.js 22.13+ (22.x), 24.x and 26.x.
245
+ Its launcher enables `--experimental-transform-types` on Node 22/24 and omits
246
+ the removed flag on Node 26. Node 26 only supports erasable TypeScript: use Node
247
+ 24 if your config or local imports contain enums, parameter properties or other
248
+ syntax requiring transformation. Odd-numbered and untested future majors are
249
+ rejected explicitly.
240
250
  The standalone executable has no installed Node version requirement.
241
251
 
242
252
  If you prefer to set up files yourself instead of using `init`, add the package to your own `package.json`:
@@ -589,13 +599,13 @@ modules:
589
599
 
590
600
  ```ts
591
601
  host("desktop", platforms.windows(), ({ windows }) => {
592
- const developerMode = windows.setting({ DeveloperMode: true });
602
+ windows.setting({ DeveloperMode: true });
593
603
  const icons = windows.powershell.module("Terminal-Icons");
594
604
 
595
605
  windows.file.symlink(
596
606
  windows.knownFolder.documents("PowerShell\\Microsoft.PowerShell_profile.ps1"),
597
607
  "../windows/powershell/Microsoft.PowerShell_profile.ps1",
598
- { backup: true, dependsOn: [icons, developerMode] },
608
+ { backup: true, dependsOn: icons },
599
609
  );
600
610
  });
601
611
  ```
@@ -611,6 +621,11 @@ and require the checkout to remain in place. Existing backup/force protections
611
621
  are unchanged. Direct `generateWindows(hosts, lock, configDir)` callers must
612
622
  supply `configDir` when using relative sources.
613
623
 
624
+ Symlinks automatically depend on typed `windows.setting({ DeveloperMode: true })`
625
+ resources declared anywhere in the same host. Developer Mode remains an explicit
626
+ machine-policy choice: Winix does not enable it merely because a symlink exists.
627
+ Without that declaration, symlinks still require existing Developer Mode or elevation.
628
+
614
629
  When generating in WSL, Winix uses `wslpath` to translate filesystem sources to
615
630
  Windows drive/UNC paths. Sources inside the Linux filesystem use a WSL UNC path,
616
631
  so that distribution must remain available during activation. Generation on
@@ -626,7 +641,7 @@ subsequent applies reuse pins without querying the repository.
626
641
  only selected entries; `--dry` resolves without writing. Resolution errors never
627
642
  replace existing pins. Network access is still needed for installation.
628
643
 
629
- `windows.powershell.module(name, { repository?, dependsOn? })` defaults to
644
+ `windows.powershell.module(name, { repository?, prerelease?, dependsOn? })` defaults to
630
645
  the host repository policy, otherwise PSGallery, selects stable releases, and installs the exact locked version for
631
646
  the current user. PowerShell 7 with PSResourceGet must already be available for
632
647
  resolution. Installation is idempotent and runs directly in DSC's
@@ -634,6 +649,17 @@ resolution. Installation is idempotent and runs directly in DSC's
634
649
  automatic dependency. Other versions are not removed. Profiles still import
635
650
  modules themselves; an unversioned `Import-Module` can load a newer installed
636
651
  version, so installation locking alone does not enforce session imports.
652
+ Set `prerelease: true` to allow a prerelease pin; its full version, including
653
+ the prerelease label, is locked and checked. A shared module with any stable-only
654
+ declaration remains stable-only.
655
+
656
+ `windows.setting(...)` implicitly declares `Microsoft.Windows.Settings` through
657
+ this same mechanism, with prereleases allowed and the host's repository policy
658
+ enforced. First apply adds its exact source-qualified module pin; no version
659
+ belongs in handwritten configuration. A different installed version does not
660
+ satisfy that pin. Native Settings activation and adapted-resource discovery with
661
+ multiple side-by-side module versions remain unverified; installing the pin
662
+ does not claim to force DSC's module selection.
637
663
 
638
664
  Work profiles can enforce an approved feed without changing shared features:
639
665
 
@@ -674,7 +700,6 @@ prerelease ensure behavior rather than adding a stable module lock.
674
700
 
675
701
  ```ts
676
702
  host("DESKTOP", platforms.windows(), ({ windows }) => {
677
- const runtime = windows.package("Microsoft.WSL");
678
703
  const setup = windows.wsl({
679
704
  config: {
680
705
  wsl2: { memory: "16GB", processors: 8 },
@@ -686,13 +711,15 @@ host("DESKTOP", platforms.windows(), ({ windows }) => {
686
711
  source: "nixos-wsl",
687
712
  installLocation: "D:/WSL/NixOS",
688
713
  default: true,
689
- dependsOn: [setup, runtime],
714
+ dependsOn: setup,
690
715
  });
691
716
  });
692
717
  ```
693
718
 
694
- `windows.wsl({ config?, backup?, force?, dependsOn? })` enables the WSL and
695
- Virtual Machine Platform Windows features and optionally manages `.wslconfig`.
719
+ `windows.wsl({ config?, backup?, force?, dependsOn? })` declares the `Microsoft.WSL`
720
+ package, enables the WSL and Virtual Machine Platform Windows features, and
721
+ optionally manages `.wslconfig`. The runtime uses normal package locking; a separate
722
+ `windows.package({ id: "Microsoft.WSL", ... })` can customize its package options.
696
723
  Calling `windows.wsl()` without config leaves that file untouched.
697
724
  `windows.optionalFeature(name,
698
725
  { enabled?, dependsOn? })` also supports individual optional features.
@@ -700,10 +727,10 @@ Feature changes require administrator approval. If a restart is required,
700
727
  dependent provisioning stops: restart Windows yourself and rerun `winix switch`.
701
728
  Winix never automatically restarts Windows or shuts down WSL.
702
729
 
703
- Declare both the features and `Microsoft.WSL` package in the same Windows host.
730
+ Declare `windows.wsl()` in the same Windows host as its distros.
704
731
  The distro automatically depends on the features, optional configuration file,
705
732
  and runtime package; explicit `dependsOn` also supports other handles. The setup
706
- handle covers both features and configuration when provided. Registration runs
733
+ handle covers the runtime package, features, and configuration when provided. Registration runs
707
734
  as the current Windows user, not SYSTEM;
708
735
  use the intended account rather than another administrator's credentials.
709
736
  `installLocation` accepts an absolute local-drive path, an environment-variable
@@ -722,8 +749,9 @@ import. Image updates affect **new registrations only**, never existing Linux
722
749
  filesystems. Dry generation can resolve missing pins but neither writes the lock
723
750
  nor downloads images.
724
751
 
725
- Winix refuses conflicting or unrecorded existing distros; it does not automatically
726
- adopt, replace, move, convert, or unregister them. Successful imports create
752
+ Winix creates the declared distro only when its registration is absent. It never
753
+ replaces, moves, converts, or unregisters a conflicting existing distro.
754
+ Successful imports create
727
755
  `.winix-wsl.json` in the installation directory to identify that registration.
728
756
  If import is interrupted before recording completes, inspect the existing
729
757
  registration and disk manually; Winix will not unregister it as rollback.
@@ -732,7 +760,43 @@ Only explicit `enabled: false` disables a feature. The separately declared
732
760
  WSL package follows normal package ownership/removal rules.
733
761
 
734
762
  The Windows registration name (`NixOS`) and Linux Winix host name (`wsl-work`,
735
- for example) are independent. To automate their first-run link, opt into `setup`:
763
+ for example) are independent. The **same declaration** can create a distro on a
764
+ new machine or adopt a matching existing one:
765
+
766
+ ```ts
767
+ windows.wsl();
768
+ windows.wsl.distro("NixOS", {
769
+ source: "nixos-wsl",
770
+ host: "wsl-work",
771
+ installLocation: windows.knownFolder.localAppData("Winix\\WSL\\NixOS"),
772
+ });
773
+ ```
774
+
775
+ During Windows activation, an untracked registration must be WSL 2, run NixOS,
776
+ and report the expected Linux hostname. `host` supplies that hostname and defaults
777
+ to `setup.host` when omitted. Winix normally sets Linux's hostname to its host ID;
778
+ if yours is overridden, set `host` to the actual expected hostname. Without
779
+ either hostname declaration, existing untracked distros are refused.
780
+
781
+ Matching distros are automatically recorded under the current Windows user's
782
+ Local AppData `Winix\wsl-registrations\registration-<name>.json`. Records bind the
783
+ registration GUID, actual location, and adopted hostname. An adopted distro keeps
784
+ its actual location; `installLocation` is only the creation destination. Later
785
+ runs revalidate identity and refuse changed/missing registrations, hostname
786
+ changes, or invalid tracking records. Inspect these records before manual
787
+ recovery; never remove one while activation is running. Existing Winix import
788
+ markers remain supported and retain their provisioning behavior.
789
+
790
+ Adoption checks no Git origin, user, checkout, or config files and executes no
791
+ repository code. It may start a stopped distro but never writes Linux setup
792
+ state, clones repositories, installs dependencies, changes defaults, or activates
793
+ Linux. `setup` and `default` are not applied to adopted distros, even on later
794
+ runs. Activate Linux manually. `winix check` and dry generation perform static
795
+ checks only; creation pins may still be resolved, but no distro is inspected or
796
+ adopted. Removing the declaration leaves the distro, its data, and tracking alone.
797
+ Automatic adoption is not available in preview.3.
798
+
799
+ For a **new distro**, automate its first-run link by opting into `setup`:
736
800
 
737
801
  ```ts
738
802
  windows.wsl.distro("NixOS", {
@@ -811,20 +875,20 @@ Store policy. Run from a normal Windows account, not WSL or another admin accoun
811
875
 
812
876
  ```powershell
813
877
  # Read-only: reports missing/old prerequisites and exits unsuccessfully if not ready.
814
- powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\scripts\bootstrap-windows.ps1 -Check
878
+ powershell.exe -NoProfile -File .\scripts\bootstrap-windows.ps1 -Check
815
879
  # Executable workflow: omit all Node/npm checks and installations.
816
- powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\scripts\bootstrap-windows.ps1 -Standalone -Check
817
- powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\scripts\bootstrap-windows.ps1 -Standalone
880
+ powershell.exe -NoProfile -File .\scripts\bootstrap-windows.ps1 -Standalone -Check
881
+ powershell.exe -NoProfile -File .\scripts\bootstrap-windows.ps1 -Standalone
818
882
  # Review and confirm installation/upgrade of missing or outdated prerequisites.
819
- powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\scripts\bootstrap-windows.ps1
883
+ powershell.exe -NoProfile -File .\scripts\bootstrap-windows.ps1
820
884
  # Choose NVM for Windows rather than standalone Node on NVM-based setups.
821
- powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\scripts\bootstrap-windows.ps1 -UseNvm
885
+ powershell.exe -NoProfile -File .\scripts\bootstrap-windows.ps1 -UseNvm
822
886
  ```
823
887
 
824
- `-ExecutionPolicy Bypass` applies to this process only, not the machine/user
825
- policy; organizational policy may still block execution. `-Yes` accepts bootstrap
888
+ Run scripts only through an execution route permitted by your signing and
889
+ organizational policies; the bootstrap does not override them. `-Yes` accepts bootstrap
826
890
  installation for automation. Installers may request UAC elevation. The script
827
- checks Git, Node (22.13+), npm, PowerShell (7.4+), PSResourceGet/PSGallery, DSC
891
+ checks Git, supported stable Node (22.13+/24/26), npm, PowerShell (7.4+), PSResourceGet/PSGallery, DSC
828
892
  (3.2+), and the backend's required DSC resources. Supported existing versions
829
893
  are kept; standalone installs use `Git.Git`, `OpenJS.NodeJS.LTS`,
830
894
  `Microsoft.PowerShell`, and `Microsoft.DSC` from the exact WinGet source/IDs.
@@ -918,6 +982,23 @@ requirements across activations by the same Windows account.
918
982
  Removing a host or moving a workspace does not automatically release its old
919
983
  recorded requirements.
920
984
 
985
+ After moving a checkout or renaming a host, explicitly transfer the old owner's
986
+ requirements to the current config directory and new host:
987
+
988
+ ```powershell
989
+ winix state owners
990
+ winix state migrate-owner <old-owner-id> --host new-host --dry
991
+ winix state migrate-owner <old-owner-id> --host new-host --yes
992
+ winix switch --host new-host --dry
993
+ ```
994
+
995
+ Run migration from the new config checkout. It changes inventory
996
+ metadata only, never evaluates config or activates/deletes resources. Every
997
+ resource's snapshots and removal rights, including external/unowned status, are
998
+ preserved; other owners stay recorded. The next switch still enforces shared
999
+ requirements, drift checks and removal confirmation. Migration requires `--yes`
1000
+ unless previewing with `--dry`; old owners are never discarded automatically.
1001
+
921
1002
  When packages or startup shortcuts would be removed, `switch` lists them and asks
922
1003
  `Continue with switch? [y/N]` before activation. Declining or closing the prompt
923
1004
  cancels the whole switch without activation or cleanup. Switches without removals
@@ -938,6 +1019,7 @@ winix state forget package winget Example.App
938
1019
  `state forget` preserves recorded requirements but releases ownership for that
939
1020
  resource across this user's inventory. If still declared, it remains required;
940
1021
  future creation or explicit shortcut replacement can grant ownership again.
1022
+ It does not fix a stale owner identity; use explicit owner migration instead.
941
1023
  Package removal requires an exact installed-version match and uses exact ID,
942
1024
  source, and version selection.
943
1025
 
@@ -31,7 +31,7 @@ import { emptyWindowsLock, reconcileInlinePins, windowsModulePin, } from "./lock
31
31
  import { isWindowsHost } from "./host.js";
32
32
  import { resolveWindowsFileProperties } from "../../helpers/windows.js";
33
33
  import { powerShellModuleProperties, powerShellRepositoryScripts } from "./powershell.js";
34
- import { powerShellRepositoryUri, resolvePowerShellModule, validateWindowsPowerShellPolicy } from "../../helpers/windows-repositories.js";
34
+ import { powerShellRepositoryUri, resolvePowerShellModule, validateWindowsPowerShellPolicy, windowsSettingsModule, } from "../../helpers/windows-repositories.js";
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";
@@ -80,6 +80,9 @@ function generateConfiguration(hostName, win, lock, configDir) {
80
80
  const repositoryDependencies = (repository) => registrations
81
81
  .filter((entry) => entry.name.toLowerCase() === repository.toLowerCase())
82
82
  .map((entry) => ({ kind: "dsc", token: entry.resource.token }));
83
+ const developerModeRefs = (win.dsc ?? [])
84
+ .filter((resource) => resource.winix?.kind === "setting" && resource.properties?.DeveloperMode === true)
85
+ .map((resource) => ({ kind: "dsc", token: resource.token }));
83
86
  const resources = (win.dsc ?? []).map((resource) => {
84
87
  const metadata = resource.winix;
85
88
  if (metadata?.kind === "file") {
@@ -87,7 +90,9 @@ function generateConfiguration(hostName, win, lock, configDir) {
87
90
  if (metadata.wslConfig && properties) {
88
91
  properties.setScript += "\nWrite-Warning 'WSL configuration changed. Restart WSL manually when safe; Winix will not stop running distros.'";
89
92
  }
90
- return cloneDscResource(resource, properties);
93
+ return cloneDscResource(resource, properties, metadata.action === "symlink"
94
+ ? [...(resource.dependsOn ?? []), ...developerModeRefs]
95
+ : resource.dependsOn);
91
96
  }
92
97
  if (metadata?.kind === "optional-features") {
93
98
  return cloneDscResource(resource, optionalFeatureProperties(metadata.names, metadata.enabled));
@@ -118,8 +123,10 @@ function generateConfiguration(hostName, win, lock, configDir) {
118
123
  }
119
124
  return resource;
120
125
  });
121
- const settingsModule = resolvePowerShellModule(win, { name: "Microsoft.Windows.Settings" });
122
- const prepared = prepareWindowsDscResources(win.commands ?? [], resources, settingsModule.repository, repositoryDependencies(settingsModule.repository));
126
+ const settingsModule = windowsSettingsModule(win);
127
+ const prepared = prepareWindowsDscResources(win.commands ?? [], resources, settingsModule, lock, [...repositoryDependencies(settingsModule.repository),
128
+ ...packages.filter((pkg) => pkg.id.toLowerCase() === "microsoft.powershell")
129
+ .map((pkg) => ({ kind: "package", id: pkg.id }))]);
123
130
  const commands = prepared.commands;
124
131
  const dscResources = [...registrations.map((entry) => entry.resource), ...prepared.dscResources];
125
132
  const lines = [];
@@ -196,18 +203,21 @@ export function validateWindowsWslResources(win) {
196
203
  if (configs > 1)
197
204
  throw new Error("Declare only one windows.wsl({ config }) per Windows host");
198
205
  if (distros && !WSL_FEATURES.every((name) => features.get(name) === true)) {
199
- throw new Error("WSL distro provisioning requires windows.wsl() or both required optional features enabled");
206
+ throw new Error("WSL distro declarations require windows.wsl() or both required optional features enabled");
200
207
  }
201
208
  if (distros && !Object.values(win.packages ?? {}).some((pkg) => pkg.id.toLowerCase() === "microsoft.wsl")) {
202
- throw new Error('WSL distro provisioning requires windows.package("Microsoft.WSL")');
209
+ throw new Error('WSL distro declarations require windows.package("Microsoft.WSL")');
203
210
  }
204
211
  }
205
- function prepareWindowsDscResources(commands, resources, settingsRepository, repositoryDependencies) {
212
+ function prepareWindowsDscResources(commands, resources, settingsModule, lock, repositoryDependencies) {
206
213
  const envResolvedResources = resolveManagedEnvironmentReferences(resources);
207
214
  if (!envResolvedResources.some((resource) => resource.winix?.kind === "setting")) {
208
215
  return { commands: [...commands], dscResources: envResolvedResources };
209
216
  }
210
- const ensureModule = createWindowsSettingsEnsureCommand(settingsRepository, repositoryDependencies);
217
+ const pin = windowsModulePin(lock, settingsModule);
218
+ if (!pin)
219
+ throw new Error('PowerShell module "Microsoft.Windows.Settings" has no matching pin in winix-windows.lock. Run winix update --windows.');
220
+ const ensureModule = createWindowsSettingsEnsureCommand(settingsModule, pin, repositoryDependencies);
211
221
  const ensureRef = { kind: "dsc", token: ensureModule.token };
212
222
  return {
213
223
  commands: [...commands],
@@ -224,31 +234,12 @@ function prepareWindowsDscResources(commands, resources, settingsRepository, rep
224
234
  ],
225
235
  };
226
236
  }
227
- function createWindowsSettingsEnsureCommand(repository, dependsOn) {
228
- // Microsoft.Windows.Settings currently publishes the WindowsSettings resource
229
- // as a prerelease module (the upstream sample uses v0.1.0-alpha), so the
230
- // ensure step must opt into prerelease discovery for now. Revisit/remove
231
- // -Prerelease once a stable module exists so future alphas are not preferred.
237
+ function createWindowsSettingsEnsureCommand(module, pin, dependsOn) {
232
238
  const resource = {
233
239
  name: WINDOWS_SETTINGS_MODULE_COMMAND_NAME,
234
- resourceType: RUN_COMMAND_ON_SET_TYPE,
240
+ resourceType: "Microsoft.DSC.Transitional/PowerShellScript",
235
241
  dependsOn,
236
- properties: {
237
- executable: "pwsh",
238
- arguments: {
239
- "0": "-NoProfile",
240
- "1": "-NoLogo",
241
- "2": "-Command",
242
- "3": [
243
- "$ErrorActionPreference = 'Stop';",
244
- "if (-not (Get-Module -ListAvailable -Name Microsoft.Windows.Settings)) {",
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' }",
247
- "}",
248
- ].join(" "),
249
- treatAsArray: true,
250
- },
251
- },
242
+ properties: powerShellModuleProperties(module, pin),
252
243
  };
253
244
  Object.defineProperty(resource, "token", {
254
245
  value: Symbol("winix.windows-settings-module"),
@@ -502,7 +493,7 @@ function resolveDependsOnRefs(refs, naming) {
502
493
  }
503
494
  ids.push(target.name);
504
495
  }
505
- return ids;
496
+ return [...new Set(ids)];
506
497
  }
507
498
  /**
508
499
  * Render one package as a DSC v3 `Microsoft.WinGet/Package` resource.
@@ -33,7 +33,7 @@ export interface WindowsLockModule {
33
33
  version: string;
34
34
  resolvedAt: string;
35
35
  }
36
- export type WindowsModuleVersionResolver = (name: string, repository: string, repositoryUri?: string) => string;
36
+ export type WindowsModuleVersionResolver = (name: string, repository: string, repositoryUri?: string, prerelease?: boolean) => string;
37
37
  export declare function windowsModuleKey(module: ResolvedPowerShellModule): string;
38
38
  export declare function windowsModulePin(lock: WindowsLock, module: ResolvedPowerShellModule): WindowsLockModule | undefined;
39
39
  export type WindowsPackageVersionResolver = (id: string, source: WinPackageSource) => string;
@@ -59,10 +59,10 @@ export declare function windowsLockChanged(before: WindowsLock, after: WindowsLo
59
59
  export declare function serializeWindowsLock(lock: WindowsLock): string;
60
60
  export declare function collectWindowsModules(hosts: EvaluatedHost[]): Map<string, ResolvedPowerShellModule>;
61
61
  export declare function hasWindowsWslDistros(hosts: EvaluatedHost[]): boolean;
62
- export declare function resolveWindowsWslImages(lock: WindowsLock, resolve: WindowsWslImageResolver, now?: Date, missingOnly?: boolean): {
62
+ export declare function resolveWindowsWslImages(lock: WindowsLock, resolve: WindowsWslImageResolver, now?: Date, missingOnly?: boolean): Promise<{
63
63
  lock: WindowsLock;
64
64
  changed: boolean;
65
- };
65
+ }>;
66
66
  export declare function resolveWindowsWslRepositories(lock: WindowsLock, hosts: EvaluatedHost[], resolve: WindowsWslRepositoryResolver, now?: Date, missingOnly?: boolean): {
67
67
  lock: WindowsLock;
68
68
  changed: boolean;
@@ -3,7 +3,7 @@ import { join } from "node:path";
3
3
  import { createHash } from "node:crypto";
4
4
  import { validWslImage } from "./wsl.js";
5
5
  import { validWslRepository, wslRepositoryKey, } from "./wsl-setup.js";
6
- import { resolvePowerShellModule, powerShellRepositoryUri, } from "../../helpers/windows-repositories.js";
6
+ import { resolvePowerShellModule, powerShellRepositoryUri, powerShellModuleVersion, windowsSettingsModule, } from "../../helpers/windows-repositories.js";
7
7
  export const WINDOWS_LOCKFILE_NAME = "winix-windows.lock";
8
8
  export const WINDOWS_LOCK_VERSION = 1;
9
9
  export function windowsModuleKey(module) {
@@ -19,7 +19,8 @@ export function windowsModulePin(lock, module) {
19
19
  const pin = lock.modules?.[windowsModuleKey(module)] ??
20
20
  (!module.repositoryUri ? lock.modules?.[module.name.toLowerCase()] : undefined);
21
21
  if (pin?.repository.toLowerCase() !== module.repository.toLowerCase() ||
22
- pin?.repositoryUri !== module.repositoryUri)
22
+ pin?.repositoryUri !== module.repositoryUri ||
23
+ (!module.prerelease && pin.version.includes("-")))
23
24
  return undefined;
24
25
  return pin;
25
26
  }
@@ -183,17 +184,18 @@ export function collectWindowsModules(hosts) {
183
184
  for (const host of hosts) {
184
185
  const win = host.windows;
185
186
  const hostModules = new Map();
186
- for (const resource of win.dsc ?? []) {
187
- if (resource.winix?.kind !== "powershell-module")
188
- continue;
189
- const module = resolvePowerShellModule(win, resource.winix.module);
187
+ const declared = (win.dsc ?? []).flatMap((resource) => resource.winix?.kind === "powershell-module" ? [resolvePowerShellModule(win, resource.winix.module)] : []);
188
+ if (win.dsc?.some((resource) => resource.winix?.kind === "setting"))
189
+ declared.push(windowsSettingsModule(win));
190
+ for (const module of declared) {
190
191
  const key = windowsModuleKey(module);
191
192
  const existing = hostModules.get(module.name.toLowerCase());
192
193
  if (existing && existing !== key) {
193
194
  throw new Error(`PowerShell module "${module.name}" is declared with conflicting repositories.`);
194
195
  }
195
196
  hostModules.set(module.name.toLowerCase(), key);
196
- modules.set(key, module);
197
+ const previous = modules.get(key);
198
+ modules.set(key, previous ? { ...module, prerelease: !!previous.prerelease && !!module.prerelease } : module);
197
199
  }
198
200
  }
199
201
  return modules;
@@ -201,14 +203,14 @@ export function collectWindowsModules(hosts) {
201
203
  export function hasWindowsWslDistros(hosts) {
202
204
  return hosts.some((host) => host.windows.dsc?.some((resource) => resource.winix?.kind === "wsl-distro"));
203
205
  }
204
- export function resolveWindowsWslImages(lock, resolve, now = new Date(), missingOnly = false) {
206
+ export async function resolveWindowsWslImages(lock, resolve, now = new Date(), missingOnly = false) {
205
207
  const images = { ...lock.wslImages };
206
208
  let changed = false;
207
209
  for (const architecture of ["x64", "arm64"]) {
208
210
  const key = `nixos-wsl/${architecture}`;
209
211
  if (missingOnly && images[key])
210
212
  continue;
211
- const image = { ...resolve(architecture), resolvedAt: now.toISOString() };
213
+ const image = { ...await resolve(architecture), resolvedAt: now.toISOString() };
212
214
  if (!validWslImage(image) || image.architecture !== architecture) {
213
215
  throw new Error(`Invalid NixOS-WSL image resolution for ${architecture}`);
214
216
  }
@@ -262,9 +264,9 @@ export function resolveWindowsModuleLockEntries(lock, modules, resolveVersion, n
262
264
  if (missingOnly && previous) {
263
265
  continue;
264
266
  }
265
- const version = resolveVersion(module.name, module.repository, module.repositoryUri);
266
- if (!/^\d+\.\d+\.\d+(?:\.\d+)?$/.test(version)) {
267
- throw new Error(`PowerShell module "${module.name}" resolver did not return a stable version: ${version}`);
267
+ const version = resolveVersion(module.name, module.repository, module.repositoryUri, !!module.prerelease);
268
+ if (!powerShellModuleVersion.test(version) || (!module.prerelease && version.includes("-"))) {
269
+ throw new Error(`PowerShell module "${module.name}" resolver did not return an allowed version: ${version}`);
268
270
  }
269
271
  const unchanged = previous?.version === version &&
270
272
  previous.repository.toLowerCase() === module.repository.toLowerCase();
@@ -335,9 +337,9 @@ function validateWindowsLock(value) {
335
337
  for (const [name, entry] of Object.entries(value.modules)) {
336
338
  if (!/^[a-z0-9][a-z0-9._-]*(?:@[a-z0-9][a-z0-9._-]*(?:\/[a-f0-9]{64})?)?$/i.test(name) || !isObject(entry) ||
337
339
  typeof entry.repository !== "string" || !/^[a-z0-9][a-z0-9._-]*$/i.test(entry.repository) ||
338
- typeof entry.version !== "string" || !/^\d+\.\d+\.\d+(?:\.\d+)?$/.test(entry.version) ||
340
+ typeof entry.version !== "string" || !powerShellModuleVersion.test(entry.version) ||
339
341
  typeof entry.resolvedAt !== "string") {
340
- throw new Error(`${WINDOWS_LOCKFILE_NAME} module "${name}" has an invalid repository, stable version, or resolvedAt.`);
342
+ throw new Error(`${WINDOWS_LOCKFILE_NAME} module "${name}" has an invalid repository, version, or resolvedAt.`);
341
343
  }
342
344
  if (entry.repositoryUri !== undefined &&
343
345
  (typeof entry.repositoryUri !== "string" || powerShellRepositoryUri(entry.repositoryUri) !== entry.repositoryUri)) {
@@ -7,5 +7,5 @@ export declare function powerShellRepositoryScripts(name: string, uri: string):
7
7
  };
8
8
  export type PowerShellGalleryRunner = (script: string) => string;
9
9
  /** Find-PSResource returns the newest stable release unless -Prerelease is requested. */
10
- export declare function resolvePowerShellModuleVersion(name: string, repository: string, repositoryUriOrRunner?: string | PowerShellGalleryRunner, runner?: PowerShellGalleryRunner): string;
10
+ export declare function resolvePowerShellModuleVersion(name: string, repository: string, repositoryUriOrRunner?: string | PowerShellGalleryRunner, prereleaseOrRunner?: boolean | PowerShellGalleryRunner, runner?: PowerShellGalleryRunner): string;
11
11
  export declare function powerShellModuleProperties(module: WinPowerShellModule, pin: WindowsLockModule): WinDscProperties;
@@ -1,5 +1,6 @@
1
1
  import { execFileSync } from "node:child_process";
2
2
  import { powerShellLiteral } from "../../helpers/utils.js";
3
+ import { powerShellModuleVersion } from "../../helpers/windows-repositories.js";
3
4
  export function powerShellRepositoryScripts(name, uri) {
4
5
  const prelude = [
5
6
  "$ErrorActionPreference = 'Stop'",
@@ -18,21 +19,25 @@ export function powerShellRepositoryScripts(name, uri) {
18
19
  };
19
20
  }
20
21
  /** Find-PSResource returns the newest stable release unless -Prerelease is requested. */
21
- export function resolvePowerShellModuleVersion(name, repository, repositoryUriOrRunner, runner) {
22
+ export function resolvePowerShellModuleVersion(name, repository, repositoryUriOrRunner, prereleaseOrRunner = false, runner) {
22
23
  const repositoryUri = typeof repositoryUriOrRunner === "string" ? repositoryUriOrRunner : undefined;
23
- const run = (typeof repositoryUriOrRunner === "function" ? repositoryUriOrRunner : runner) ??
24
+ const prerelease = prereleaseOrRunner === true;
25
+ const run = (typeof repositoryUriOrRunner === "function" ? repositoryUriOrRunner :
26
+ typeof prereleaseOrRunner === "function" ? prereleaseOrRunner : runner) ??
24
27
  ((script) => execFileSync("pwsh", ["-NoLogo", "-NoProfile", "-NonInteractive", "-EncodedCommand", encode(script)], { encoding: "utf8" }));
25
28
  const script = [
26
29
  "$ErrorActionPreference = 'Stop'",
27
30
  ...(repositoryUri ? [powerShellRepositoryScripts(repository, repositoryUri).set] : []),
28
- `$found = @(Find-PSResource -Name ${powerShellLiteral(name)} -Repository ${powerShellLiteral(repository)} -ErrorAction Stop)`,
29
- `if ($found.Count -ne 1 -or $found[0].Name -ine ${powerShellLiteral(name)} -or $found[0].Prerelease) { throw 'Expected one stable module release' }`,
30
- "$found[0].Version.ToString() | ConvertTo-Json -Compress",
31
+ `$found = @(Find-PSResource -Name ${powerShellLiteral(name)} -Repository ${powerShellLiteral(repository)}${prerelease ? " -Prerelease" : ""} -ErrorAction Stop)`,
32
+ `if ($found.Count -ne 1 -or $found[0].Name -ine ${powerShellLiteral(name)}${prerelease ? "" : " -or $found[0].Prerelease"}) { throw 'Expected one matching module release' }`,
33
+ "$version = $found[0].Version.ToString()",
34
+ "if ($found[0].Prerelease) { $version += '-' + $found[0].Prerelease }",
35
+ "$version | ConvertTo-Json -Compress",
31
36
  ].join("\n");
32
37
  try {
33
38
  const version = JSON.parse(run(script).trim());
34
- if (typeof version !== "string" || !/^\d+\.\d+\.\d+(?:\.\d+)?$/.test(version)) {
35
- throw new Error("Repository did not return a stable module version");
39
+ if (typeof version !== "string" || !powerShellModuleVersion.test(version) || (!prerelease && version.includes("-"))) {
40
+ throw new Error("Repository did not return an allowed module version");
36
41
  }
37
42
  return version;
38
43
  }
@@ -46,11 +51,17 @@ function encode(script) {
46
51
  return Buffer.from(script, "utf16le").toString("base64");
47
52
  }
48
53
  export function powerShellModuleProperties(module, pin) {
54
+ if (!powerShellModuleVersion.test(pin.version) || (!module.prerelease && pin.version.includes("-"))) {
55
+ throw new Error(`Module ${module.name} has an invalid or disallowed version pin`);
56
+ }
57
+ const [version, prerelease = ""] = pin.version.split(/-(.*)/s);
49
58
  const variables = [
50
59
  `$name = ${powerShellLiteral(module.name)}`,
51
60
  `$version = ${powerShellLiteral(pin.version)}`,
61
+ `$baseVersion = ${powerShellLiteral(version)}`,
62
+ `$prerelease = ${powerShellLiteral(prerelease)}`,
52
63
  ];
53
- const present = "@(Get-Module -ListAvailable -Name $name | Where-Object { $_.Version -eq [version]$version -and -not $_.PrivateData.PSData.Prerelease }).Count -gt 0";
64
+ const present = "@(Get-Module -ListAvailable -Name $name | Where-Object { $_.Version -eq [version]$baseVersion -and [string]$_.PrivateData.PSData.Prerelease -ceq $prerelease }).Count -gt 0";
54
65
  const prelude = [
55
66
  "$ErrorActionPreference = 'Stop'",
56
67
  "if ($PSVersionTable.PSVersion.Major -lt 7) { throw 'PowerShell 7 is required' }",
@@ -65,7 +76,7 @@ export function powerShellModuleProperties(module, pin) {
65
76
  setScript: [
66
77
  ...prelude,
67
78
  `if (${present}) { return }`,
68
- `Install-PSResource -Name $name -Version $version -Repository ${powerShellLiteral(pin.repository)} -Scope CurrentUser -TrustRepository -AcceptLicense -Reinstall -ErrorAction Stop | Out-Null`,
79
+ `Install-PSResource -Name $name -Version $version -Repository ${powerShellLiteral(pin.repository)}${prerelease ? " -Prerelease" : ""} -Scope CurrentUser -TrustRepository -AcceptLicense -Reinstall -ErrorAction Stop | Out-Null`,
69
80
  `if (-not (${present})) { throw "Module $name $version was not installed" }`,
70
81
  ].join("\n"),
71
82
  };
@@ -10,3 +10,4 @@ export declare function wslRepositoryKey(setup: WinWslSetup): string;
10
10
  export declare function validWslRepository(value: unknown): value is WindowsLockWslRepository;
11
11
  export declare const resolveWslRepository: WindowsWslRepositoryResolver;
12
12
  export declare function wslSetupPrelude(setup: WinWslSetup, pin: WindowsLockWslRepository): string[];
13
+ export declare function wslScriptInvocation(name: string, probe: string, activate: string, operation?: string): string[];
@@ -99,7 +99,7 @@ export function wslSetupPrelude(setup, pin) {
99
99
  const extension = import.meta.url.endsWith(".ts") ? "ts" : "js";
100
100
  const source = readFileSync(new URL(`./wsl-setup-runtime.${extension}`, import.meta.url), "utf8");
101
101
  const runtime = extension === "ts"
102
- ? createRequire(import.meta.url)("node:module").stripTypeScriptTypes(source, { mode: "transform" })
102
+ ? createRequire(import.meta.url)("node:module").stripTypeScriptTypes(source, { mode: "strip" })
103
103
  : source;
104
104
  launch = [
105
105
  `export WINIX_WSL_SETUP_RUNTIME='${Buffer.from(runtime + "\nawait dispatchWslSetup();\n").toString("base64")}'`,
@@ -125,24 +125,28 @@ export function wslSetupPrelude(setup, pin) {
125
125
  'export NIX_CONFIG="${NIX_CONFIG:+$NIX_CONFIG$\'\\n\'}extra-experimental-features = nix-command flakes"',
126
126
  ...launch,
127
127
  ].join("\n");
128
+ return wslScriptInvocation("Invoke-WinixWslSetup", probe, activate);
129
+ }
130
+ export function wslScriptInvocation(name, probe, activate, operation = "WSL setup") {
128
131
  return [
129
- "function Invoke-WinixWslSetup([bool]$TestOnly) {",
132
+ `function ${name}([bool]$TestOnly) {`,
133
+ ` $operation = ${ps(operation)}`,
130
134
  ` $script = if ($TestOnly) { ${ps(probe + "\n")} } else { ${ps(activate + "\n")} }`,
131
135
  " $start = [Diagnostics.ProcessStartInfo]::new('wsl.exe')",
132
136
  " $start.UseShellExecute = $false",
133
137
  " $start.RedirectStandardInput = $true; $start.RedirectStandardOutput = $true; $start.RedirectStandardError = $true",
134
138
  " $start.StandardInputEncoding = [Text.UTF8Encoding]::new($false)",
135
139
  " $start.StandardOutputEncoding = $start.StandardInputEncoding; $start.StandardErrorEncoding = $start.StandardInputEncoding",
136
- " foreach ($argument in @('--distribution', $name, '--user', 'root', '--exec', 'bash', '-s')) { $start.ArgumentList.Add($argument) }",
140
+ " foreach ($argument in @('--distribution', $name, '--user', 'root', '--exec', 'bash', '--noprofile', '--norc', '-s')) { $start.ArgumentList.Add($argument) }",
137
141
  " $process = [Diagnostics.Process]::new(); $process.StartInfo = $start",
138
142
  " try {",
139
- " if (-not $process.Start()) { throw 'Could not start WSL setup' }",
143
+ " if (-not $process.Start()) { throw \"Could not start $operation\" }",
140
144
  " $stdout = $process.StandardOutput.ReadToEndAsync(); $stderr = $process.StandardError.ReadToEndAsync()",
141
145
  " $process.StandardInput.Write($script); $process.StandardInput.Close()",
142
146
  " $process.WaitForExit()",
143
147
  " $output = $stdout.GetAwaiter().GetResult(); $errors = $stderr.GetAwaiter().GetResult()",
144
148
  " if ($TestOnly -and $process.ExitCode -eq 3) { return $false }",
145
- " if ($process.ExitCode -ne 0) { throw \"WSL setup failed ($($process.ExitCode)): $output $errors\" }",
149
+ " if ($process.ExitCode -ne 0) { throw \"$operation failed ($($process.ExitCode)): $output $errors\" }",
146
150
  " if (-not $TestOnly) { if ($output) { Write-Host $output }; if ($errors) { Write-Host $errors } }",
147
151
  " return $true",
148
152
  " } finally { $process.Dispose() }",
@@ -2,8 +2,9 @@ import type { WinDscProperties, WinWslDistro } from "../../types/index.js";
2
2
  import type { WindowsLockWslImage } from "./lockfile.js";
3
3
  import { type WindowsLockWslRepository } from "./wsl-setup.js";
4
4
  export type WslArchitecture = "x64" | "arm64";
5
- export type WindowsWslImageResolver = (architecture: WslArchitecture) => Omit<WindowsLockWslImage, "resolvedAt">;
5
+ export type WindowsWslImageResolver = (architecture: WslArchitecture) => Omit<WindowsLockWslImage, "resolvedAt"> | Promise<Omit<WindowsLockWslImage, "resolvedAt">>;
6
6
  export declare function validWslImage(value: unknown): value is WindowsLockWslImage;
7
7
  export declare const resolveNixosWslImage: WindowsWslImageResolver;
8
8
  export declare function optionalFeatureProperties(names: string[], enabled: boolean): WinDscProperties;
9
+ export declare function wslIdentityProbe(host: string): string;
9
10
  export declare function wslDistroProperties(distro: WinWslDistro, pins: Record<string, WindowsLockWslImage>, repositories?: Record<string, WindowsLockWslRepository>): WinDscProperties;