@adrifer/winix 0.2.3 → 0.2.4-preview.0

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.
Files changed (36) hide show
  1. package/README.md +364 -2
  2. package/dist/backends/windows/index.d.ts +3 -1
  3. package/dist/backends/windows/index.js +99 -7
  4. package/dist/backends/windows/lockfile.d.ts +36 -1
  5. package/dist/backends/windows/lockfile.js +168 -0
  6. package/dist/backends/windows/paths.d.ts +2 -0
  7. package/dist/backends/windows/paths.js +17 -0
  8. package/dist/backends/windows/powershell.d.ts +6 -0
  9. package/dist/backends/windows/powershell.js +51 -0
  10. package/dist/backends/windows/wsl-setup-runtime.d.ts +32 -0
  11. package/dist/backends/windows/wsl-setup-runtime.js +387 -0
  12. package/dist/backends/windows/wsl-setup.d.ts +12 -0
  13. package/dist/backends/windows/wsl-setup.js +108 -0
  14. package/dist/backends/windows/wsl.d.ts +9 -0
  15. package/dist/backends/windows/wsl.js +194 -0
  16. package/dist/cli/commands/apply.d.ts +7 -1
  17. package/dist/cli/commands/apply.js +39 -15
  18. package/dist/cli/commands/check.js +3 -0
  19. package/dist/cli/commands/switch.d.ts +6 -0
  20. package/dist/cli/commands/switch.js +53 -13
  21. package/dist/cli/commands/update.d.ts +6 -1
  22. package/dist/cli/commands/update.js +41 -10
  23. package/dist/cli/index.js +33 -2
  24. package/dist/cli/windows-state.d.ts +56 -0
  25. package/dist/cli/windows-state.js +341 -0
  26. package/dist/helpers/index.d.ts +1 -1
  27. package/dist/helpers/utils.d.ts +1 -0
  28. package/dist/helpers/utils.js +8 -0
  29. package/dist/helpers/windows.d.ts +53 -7
  30. package/dist/helpers/windows.js +351 -28
  31. package/dist/index.d.ts +4 -2
  32. package/dist/skill.js +114 -5
  33. package/dist/types/windows.d.ts +82 -1
  34. package/package.json +3 -1
  35. package/scripts/bootstrap-nixos.sh +51 -0
  36. package/scripts/bootstrap-windows.ps1 +216 -0
package/README.md CHANGED
@@ -126,6 +126,36 @@ You can also install it globally, but local project installs are recommended:
126
126
  npm install -g @adrifer/winix
127
127
  ```
128
128
 
129
+ ### Bootstrap prerequisites on NixOS
130
+
131
+ On an existing NixOS installation (including NixOS-WSL), a reviewed copy of
132
+ `scripts/bootstrap-nixos.sh` opens a temporary prerequisite environment:
133
+
134
+ ```bash
135
+ bash bootstrap-nixos.sh
136
+ # Inside the shell, clone your config, install its dependencies, and run Winix yourself.
137
+ # Type exit when finished.
138
+ ```
139
+
140
+ Git, Node.js 24/npm, and interactive Bash come from one nixpkgs commit pinned
141
+ in the script, without relying on your channels or flake registry. The script
142
+ enables `nix-command`/flakes for the child session only and disables Bash startup
143
+ files so user profiles cannot replace the bootstrap PATH. The working directory
144
+ is preserved. Network/store access is required on a cold machine; normal Nix
145
+ permissions, cache verification, and trust settings still apply.
146
+
147
+ Nothing is installed into a user profile or system configuration, though Nix
148
+ may download packages into its store. The script does not install NixOS, clone
149
+ a repo, install Winix/npm dependencies, select a host, or rebuild anything.
150
+ Declare tools and Nix settings in your own config for permanent availability.
151
+ Maintainers update the pinned nixpkgs commit deliberately alongside the script.
152
+
153
+ Future stable and preview [GitHub releases](https://github.com/adrifer/winix/releases)
154
+ include `bootstrap-nixos.sh` and `bootstrap-nixos.sh.sha256`. Download both,
155
+ check with `sha256sum --check bootstrap-nixos.sh.sha256`, review the script, then
156
+ run it; do not pipe an unreviewed download into a shell. Checksums detect
157
+ corruption but do not independently establish publisher identity.
158
+
129
159
  ## CLI
130
160
 
131
161
  From a Winix project:
@@ -417,8 +447,340 @@ host("desktop", platforms.windows(), ({ windows }) => {
417
447
  });
418
448
  ```
419
449
 
420
- This generates a DSC v3 document that `winget configure` applies. The backend is
421
- an MVP: only `windows.package` and `windows.raw` exist today. See
450
+ This generates a DSC v3 document that `winget configure` applies. Typed helpers
451
+ also cover environment variables, PATH, files, Windows settings, and PowerShell
452
+ modules:
453
+
454
+ ```ts
455
+ host("desktop", platforms.windows(), ({ windows }) => {
456
+ const developerMode = windows.setting({ DeveloperMode: true });
457
+ const icons = windows.powershell.module("Terminal-Icons");
458
+
459
+ windows.file.symlink(
460
+ windows.knownFolder.documents("PowerShell\\Microsoft.PowerShell_profile.ps1"),
461
+ "../windows/powershell/Microsoft.PowerShell_profile.ps1",
462
+ { backup: true, dependsOn: [icons, developerMode] },
463
+ );
464
+ });
465
+ ```
466
+
467
+ `windows.knownFolder.documents(childPath?)` resolves redirected Documents **during activation**,
468
+ not on the machine generating the configuration. Supported folders are
469
+ `documents`, `desktop`, `localAppData`, `appData`, and `userProfile`. The optional
470
+ child path must stay within the folder. All `windows.file.*` targets accept it.
471
+ Copy/symlink source strings are relative to the directory containing
472
+ `winix.config.ts`, not the calling feature or working directory. Absolute paths,
473
+ `%VARIABLE%` paths, and `file:` URL objects remain supported. Symlinks stay live
474
+ and require the checkout to remain in place. Existing backup/force protections
475
+ are unchanged. Direct `generateWindows(hosts, lock, configDir)` callers must
476
+ supply `configDir` when using relative sources.
477
+
478
+ When generating in WSL, Winix uses `wslpath` to translate filesystem sources to
479
+ Windows drive/UNC paths. Sources inside the Linux filesystem use a WSL UNC path,
480
+ so that distribution must remain available during activation. Generation on
481
+ other Linux/macOS systems does not translate local paths; use Windows-reachable
482
+ absolute or environment-variable sources when generating there.
483
+
484
+ PowerShell module versions and repositories are pinned in the optional `modules`
485
+ section of the existing `winix-windows.lock` (lowercase module-name keys).
486
+ Old package-only locks remain valid. First apply resolves missing entries;
487
+ subsequent applies reuse pins without querying the repository.
488
+ `winix update --windows` refreshes packages and modules, or pass names to update
489
+ only selected entries; `--dry` resolves without writing. Resolution errors never
490
+ replace existing pins. Network access is still needed for installation.
491
+
492
+ `windows.powershell.module(name, { repository?, dependsOn? })` defaults to
493
+ PSGallery, selects stable releases, and installs the exact locked version for
494
+ the current user. PowerShell 7 with PSResourceGet must already be available for
495
+ resolution. Installation is idempotent and runs directly in DSC's
496
+ `Microsoft.DSC.Transitional/PowerShellScript` resource; a declared `Microsoft.PowerShell` package is an
497
+ automatic dependency. Other versions are not removed. Profiles still import
498
+ modules themselves; an unversioned `Import-Module` can load a newer installed
499
+ version, so installation locking alone does not enforce session imports.
500
+
501
+ ### Provision WSL from a Windows host
502
+
503
+ ```ts
504
+ host("DESKTOP", platforms.windows(), ({ windows }) => {
505
+ const runtime = windows.package("Microsoft.WSL");
506
+ const setup = windows.wsl({
507
+ config: {
508
+ wsl2: { memory: "16GB", processors: 8 },
509
+ experimental: { autoMemoryReclaim: "gradual" },
510
+ },
511
+ backup: true,
512
+ });
513
+ windows.wsl.distro("NixOS", {
514
+ source: "nixos-wsl",
515
+ installLocation: "D:/WSL/NixOS",
516
+ default: true,
517
+ dependsOn: [setup, runtime],
518
+ });
519
+ });
520
+ ```
521
+
522
+ `windows.wsl({ config?, backup?, force?, dependsOn? })` enables the WSL and
523
+ Virtual Machine Platform Windows features and optionally manages `.wslconfig`.
524
+ Calling `windows.wsl()` without config leaves that file untouched.
525
+ `windows.optionalFeature(name,
526
+ { enabled?, dependsOn? })` also supports individual optional features.
527
+ Feature changes require administrator approval. If a restart is required,
528
+ dependent provisioning stops: restart Windows yourself and rerun `winix switch`.
529
+ Winix never automatically restarts Windows or shuts down WSL.
530
+
531
+ Declare both the features and `Microsoft.WSL` package in the same Windows host.
532
+ The distro automatically depends on the features, optional configuration file,
533
+ and runtime package; explicit `dependsOn` also supports other handles. The setup
534
+ handle covers both features and configuration when provided. Registration runs
535
+ as the current Windows user, not SYSTEM;
536
+ use the intended account rather than another administrator's credentials.
537
+ `installLocation` accepts an absolute local-drive path, an environment-variable
538
+ path, or a known-folder target. It must not already exist. Names and locations
539
+ must be unique per host; at most one distro may be declared default.
540
+
541
+ The `config` option owns the current user's complete `.wslconfig`, using the
542
+ normal file backup/force protections. Changes print a reminder to restart WSL
543
+ manually when safe. They do not immediately alter running distros.
544
+
545
+ First apply pins official stable NixOS-WSL image URLs and SHA256 digests for x64
546
+ and ARM64 in the optional `wslImages` section of `winix-windows.lock`. Subsequent
547
+ applies reuse these pins. `winix update --windows nixos-wsl` refreshes them;
548
+ updating all Windows entries includes images too. Downloads are verified before
549
+ import. Image updates affect **new registrations only**, never existing Linux
550
+ filesystems. Dry generation can resolve missing pins but neither writes the lock
551
+ nor downloads images.
552
+
553
+ Winix refuses conflicting or unrecorded existing distros; it does not automatically
554
+ adopt, replace, move, convert, or unregister them. Successful imports create
555
+ `.winix-wsl.json` in the installation directory to identify that registration.
556
+ If import is interrupted before recording completes, inspect the existing
557
+ registration and disk manually; Winix will not unregister it as rollback.
558
+ Removing declarations leaves distro data and enabled optional features intact.
559
+ Only explicit `enabled: false` disables a feature. The separately declared
560
+ WSL package follows normal package ownership/removal rules.
561
+
562
+ The Windows registration name (`NixOS`) and Linux Winix host name (`wsl-work`,
563
+ for example) are independent. To automate their first-run link, opt into `setup`:
564
+
565
+ ```ts
566
+ windows.wsl.distro("NixOS", {
567
+ source: "nixos-wsl",
568
+ installLocation: windows.knownFolder.localAppData("Winix\\WSL\\NixOS"),
569
+ default: true,
570
+ setup: {
571
+ repository: "https://github.com/example/dotfiles.git",
572
+ ref: "main",
573
+ configDirectory: "winix",
574
+ host: "wsl-work",
575
+ user: "alice",
576
+ checkout: "/home/alice/dotfiles",
577
+ },
578
+ });
579
+ ```
580
+
581
+ This explicitly trusts the repository, its npm lifecycle scripts, and its Winix
582
+ configuration. Use a committed `package.json`, `package-lock.json`, and `flake.lock`
583
+ in `configDirectory`, with a released Winix dependency supporting this API.
584
+ Only HTTPS Git URLs without embedded credentials are accepted. Private repository
585
+ and dependency authentication must already be available inside Linux; credentials
586
+ are never provisioned by this helper.
587
+
588
+ The Linux host must explicitly enable NixOS-WSL, import its input module, declare
589
+ `system.stateVersion`, and match the distro architecture. `user` selects an
590
+ already-declared normal account, not a second account definition. Omit it when
591
+ Home Manager or the sole normal account identifies the user unambiguously.
592
+ Home Manager's username/home must agree with the selected account. `checkout`
593
+ defaults to `<declared-home>/dotfiles` and must stay inside that home.
594
+
595
+ First apply locks the repository ref (default `HEAD`) to a commit in
596
+ `wslRepositories`. `winix update --windows wsl-setup` refreshes these pins;
597
+ an update without names includes them too. Dry generation never clones or executes
598
+ repository code. Pins affect **first-run setup only**, not subsequent dotfiles
599
+ updates; an interrupted setup retains its original commit.
600
+
601
+ During activation, Git/npm/config preparation runs as the image's initial `nixos`
602
+ user. A root coordinator first activates only the selected declarative account
603
+ and required WSL/shell settings, moves checkout ownership to it, then generates
604
+ the full host as that user and activates it as root. No password is invented and
605
+ sudo policy is not changed. External secret files required by the account must
606
+ already exist. The full host must set `wsl.defaultUser` to the selected user.
607
+
608
+ Setup records resumable stages under `/var/lib/winix/wsl-setup`; rerun Windows
609
+ `winix switch` after a reported failure. Dirty, occupied, or changed checkouts and
610
+ changed setup settings are refused, never reset or adopted. A killed coordinator
611
+ can leave `run.lock`: inspect its recorded PID/state and confirm no setup is
612
+ running before manually removing that lock. Other conflicts require explicit
613
+ manual recovery or a new distro. Successful setup is not repeated; later Linux
614
+ updates remain ordinary Linux Winix operations. No shutdown/reboot is performed;
615
+ restart WSL manually when safe if its new default-user setting needs it.
616
+ Fresh-image end-to-end activation remains unverified.
617
+
618
+ Without `setup`, repository installation and Linux activation remain manual.
619
+
620
+ ### Bootstrap a Windows machine
621
+
622
+ `scripts/bootstrap-windows.ps1` runs with built-in Windows PowerShell 5.1 or
623
+ PowerShell 7, without needing Node, Git, or Winix first. Save a reviewed copy
624
+ from your chosen Winix checkout/revision (or carry it on your restore drive).
625
+ Starting with the next release containing this change, stable and preview
626
+ [GitHub releases](https://github.com/adrifer/winix/releases) include
627
+ `bootstrap-windows.ps1` and `bootstrap-windows.ps1.sha256` as downloadable assets,
628
+ so no checkout, Git, or npm is needed to obtain the script. Use
629
+ `Get-FileHash .\bootstrap-windows.ps1 -Algorithm SHA256` to compare its hash with
630
+ the downloaded checksum file. The checksum detects corruption, not publisher
631
+ identity; the script is not yet code-signed.
632
+ Do not pipe an unreviewed download into a shell.
633
+
634
+ App Installer/WinGet must already be available for the current Windows account.
635
+ If missing, the script stops with the official Store link and first-sign-in
636
+ registration instructions; it does not download unsigned installers or bypass
637
+ Store policy. Run from a normal Windows account, not WSL or another admin account:
638
+
639
+ ```powershell
640
+ # Read-only: reports missing/old prerequisites and exits unsuccessfully if not ready.
641
+ powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\scripts\bootstrap-windows.ps1 -Check
642
+ # Review and confirm installation/upgrade of missing or outdated prerequisites.
643
+ powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\scripts\bootstrap-windows.ps1
644
+ # Choose NVM for Windows rather than standalone Node on NVM-based setups.
645
+ powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\scripts\bootstrap-windows.ps1 -UseNvm
646
+ ```
647
+
648
+ `-ExecutionPolicy Bypass` applies to this process only, not the machine/user
649
+ policy; organizational policy may still block execution. `-Yes` accepts bootstrap
650
+ installation for automation. Installers may request UAC elevation. The script
651
+ checks Git, Node (22.13+), npm, PowerShell (7.4+), PSResourceGet/PSGallery, DSC
652
+ (3.2+), and the backend's required DSC resources. Supported existing versions
653
+ are kept; standalone installs use `Git.Git`, `OpenJS.NodeJS.LTS`,
654
+ `Microsoft.PowerShell`, and `Microsoft.DSC` from the exact WinGet source/IDs.
655
+ `-UseNvm` installs `CoreyButler.NVMforWindows` if needed and selects Node LTS
656
+ through NVM instead. It refuses to introduce standalone Node alongside an
657
+ existing NVM installation when Node needs setup. Install mode also enables
658
+ WinGet configuration components (requires Store access); `-Check` does not.
659
+
660
+ Only the process PATH/NVM environment is refreshed; no persistent policy or
661
+ environment values are written by the script itself. Installers can change
662
+ their normal installation settings. Errors stop the bootstrap; restart requests
663
+ are reported, never performed automatically. Reopen PowerShell 7 afterward.
664
+ Bootstrap installations are prerequisites, not Winix-owned host resources, and
665
+ are not pinned by a host's Windows lockfile.
666
+
667
+ This is the reusable prerequisite layer, not a dotfiles installer. Preparing a
668
+ config checkout, restoring its npm dependencies, selecting a compatible Winix
669
+ version/local SDK, reviewing `check`/`switch --dry`, and confirming `switch` are
670
+ separate steps. It never clones repositories, installs Winix globally, activates
671
+ a host, changes execution policy persistently, or provisions WSL. Repository
672
+ setup, npm installation, and all Winix commands remain the user's responsibility.
673
+
674
+ All generated file, PATH, and module scripts use PowerShell 7; string-form
675
+ `windows.raw("...")` commands also default to `pwsh`, without loading a profile
676
+ or prompting interactively. Explicit executable choices
677
+ remain unchanged. Winix no longer requires Windows PowerShell 5.1 for these
678
+ flows, but it does not remove it from Windows.
679
+
680
+ Install PowerShell 7 and make `pwsh` available on PATH **before** DSC discovers
681
+ the configuration's resources; a `dependsOn` package alone does not bootstrap
682
+ resource discovery. Script `setScript` operations independently check current
683
+ state because the transitional resource can invoke set without first running
684
+ `testScript`. Native Registry resources still manage persistent environment
685
+ variables, with machine-scope writes requiring elevation as before.
686
+ Generated script literals escape Unicode to survive DSC's script transport
687
+ without corrupting file contents or paths.
688
+
689
+ ### Windows sign-in startup
690
+
691
+ ```ts
692
+ windows.startup.command("my-app", {
693
+ executable: "%ProgramFiles%/MyApp/app.exe",
694
+ arguments: ["--config", windows.knownFolder.appData("MyApp/config.json")],
695
+ workingDirectory: windows.knownFolder.userProfile(),
696
+ windowStyle: "minimized",
697
+ backup: true,
698
+ dependsOn: appPackage,
699
+ });
700
+ ```
701
+
702
+ `windows.startup.command(name, spec)` manages `<name>.lnk` in the current user's
703
+ actual Startup known folder. It only registers the shortcut: nothing is launched,
704
+ stopped, or reloaded during apply. Commands run at sign-in, not at machine boot;
705
+ this is not a service, scheduled task, elevated launch, or all-users startup API.
706
+
707
+ The executable may be an absolute path, an environment-variable path, a named
708
+ known-folder path, or an application name resolved on PATH during activation.
709
+ The executable and working directory must exist then; use `dependsOn` for
710
+ installation/configuration ordering. Relative filesystem paths are rejected.
711
+ The default working directory is the user profile. `arguments` is an argv array:
712
+ strings are literal (including `%VAR%`), while known-folder values resolve during
713
+ activation. Standard Windows argv quoting preserves spaces, empty arguments,
714
+ embedded quotes, backslashes, and Unicode; no shell is implicitly inserted.
715
+
716
+ `windowStyle` accepts `normal` (default), `minimized`, or `maximized`; minimized
717
+ does not guarantee a hidden console. Correct shortcuts are left untouched.
718
+ Replacement is refused by default; `backup: true` preserves an existing entry
719
+ as `.lnk.bak` and refuses backup collisions, while `force: true` opts into
720
+ replacement without a backup. A new shortcut is staged and verified before
721
+ replacing the old one. Keep names unique per host.
722
+
723
+ ### Windows removal and ownership
724
+
725
+ Native Windows `winix switch` keeps a separate applied-state inventory under
726
+ `%LOCALAPPDATA%\Winix\applied-<machine-and-user-hash>.json`. This is machine-local
727
+ state, not the version lockfile and not something to commit or copy to another
728
+ machine. Canonical workspace directories and host names identify recorded
729
+ requirements across activations by the same Windows account.
730
+
731
+ - A shortcut Winix creates or explicitly replaces becomes owned after successful
732
+ activation. Removing its declaration removes that unchanged shortcut on the
733
+ next successful switch, without stopping the running program. An already
734
+ matching, pre-existing shortcut is not automatically adopted.
735
+ - A package absent before and present after successful activation becomes owned.
736
+ Already-installed packages satisfy requirements without gaining uninstall
737
+ ownership. Removing a declaration automatically uninstalls an unused,
738
+ previously owned package after successful activation. Preview all cleanup with
739
+ `winix switch --dry`. Uninstallers may remove application data.
740
+ - External resources are never swept. Other recorded hosts/workspaces retain
741
+ their requirements; incompatible shared declarations fail before activation.
742
+ Removing a host or moving a workspace does not automatically release its old
743
+ recorded requirements.
744
+
745
+ When packages or startup shortcuts would be removed, `switch` lists them and asks
746
+ `Continue with switch? [y/N]` before activation. Declining or closing the prompt
747
+ cancels the whole switch without activation or cleanup. Switches without removals
748
+ and `--dry` do not prompt. Use `winix switch --yes` (or `-y`) to accept removals
749
+ for automation; noninteractive switches with removals require this flag.
750
+
751
+ Startup file hashes and installed package versions detect drift. External edits
752
+ or version changes block reconciliation rather than silently deleting or
753
+ overwriting managed resources. Restore the recorded resource, or explicitly
754
+ release Winix's removal rights without deleting anything:
755
+
756
+ ```powershell
757
+ winix state forget startup komorebi --dry
758
+ winix state forget startup komorebi
759
+ winix state forget package winget Example.App
760
+ ```
761
+
762
+ `state forget` preserves recorded requirements but releases ownership for that
763
+ resource across this user's inventory. If still declared, it remains required;
764
+ future creation or explicit shortcut replacement can grant ownership again.
765
+ Package removal requires an exact installed-version match and uses exact ID,
766
+ source, and version selection.
767
+
768
+ Dry Windows switches inspect and report removals without changing inventory,
769
+ system resources, or generated output. `apply`, running generated
770
+ scripts directly, or invoking `winget configure` yourself does not record
771
+ ownership or perform cleanup. A failed/interrupted activation never grants new
772
+ ownership; partial installations can remain unmanaged. Removal progress is saved
773
+ after each successful removal so failures can be retried conservatively.
774
+ Concurrent switches are refused. After a crash, inspect the inventory and
775
+ `.lock`/`.tmp` siblings before manually clearing stale files.
776
+
777
+ This coordinates recorded activations for one user/machine, not other users,
778
+ unrecorded configurations, or independent installers running concurrently.
779
+ Losing the inventory loses deletion rights; Winix does not reconstruct ownership
780
+ from installed software, existing shortcuts, generated output, or lockfiles.
781
+ Files, modules, Registry values, and PATH entries do not yet have removal tracking.
782
+
783
+ See
422
784
  [`examples/windows/`](examples/windows) and
423
785
  [`spec/proposals/windows-backend.md`](spec/proposals/windows-backend.md).
424
786
 
@@ -1,4 +1,5 @@
1
1
  import type { EvaluatedHost } from "../../evaluator/index.js";
2
+ import type { WindowsOptions } from "../../types/index.js";
2
3
  import { type WindowsLock } from "./lockfile.js";
3
4
  export { isWindowsHost } from "./host.js";
4
5
  /**
@@ -21,4 +22,5 @@ export interface WindowsOutput {
21
22
  * Generate Windows bundles for every Windows host in the evaluated workspace.
22
23
  * Non-Windows hosts are skipped.
23
24
  */
24
- export declare function generateWindows(evaluatedHosts: EvaluatedHost[], lock?: WindowsLock): WindowsOutput;
25
+ export declare function generateWindows(evaluatedHosts: EvaluatedHost[], lock?: WindowsLock, configDir?: string): WindowsOutput;
26
+ export declare function validateWindowsWslResources(win: WindowsOptions): void;
@@ -25,9 +25,15 @@
25
25
  //
26
26
  // `winget configure -f configuration.winget` runs this directly; the dscv3
27
27
  // processor is selected by the metadata block.
28
+ import { win32 } from "node:path";
28
29
  import { yamlEntry, yamlScalar } from "./yaml.js";
29
30
  import { emptyWindowsLock, reconcileInlinePins, } from "./lockfile.js";
30
31
  import { isWindowsHost } from "./host.js";
32
+ import { resolveWindowsFileProperties } from "../../helpers/windows.js";
33
+ import { powerShellModuleProperties } from "./powershell.js";
34
+ import { powerShellLiteral as psSingleQuoted } from "../../helpers/utils.js";
35
+ import { windowsSourcePath } from "./paths.js";
36
+ import { optionalFeatureProperties, wslDistroProperties } from "./wsl.js";
31
37
  export { isWindowsHost } from "./host.js";
32
38
  const DSC_SCHEMA = "https://raw.githubusercontent.com/PowerShell/DSC/main/schemas/2023/08/config/document.json";
33
39
  const WINGET_PACKAGE_TYPE = "Microsoft.WinGet/Package";
@@ -37,7 +43,7 @@ const WINDOWS_SETTINGS_MODULE_COMMAND_NAME = "Ensure Microsoft Windows Settings
37
43
  * Generate Windows bundles for every Windows host in the evaluated workspace.
38
44
  * Non-Windows hosts are skipped.
39
45
  */
40
- export function generateWindows(evaluatedHosts, lock = emptyWindowsLock()) {
46
+ export function generateWindows(evaluatedHosts, lock = emptyWindowsLock(), configDir) {
41
47
  const hosts = {};
42
48
  const warnings = [];
43
49
  const windowsHosts = evaluatedHosts.filter(isWindowsHost);
@@ -45,7 +51,7 @@ export function generateWindows(evaluatedHosts, lock = emptyWindowsLock()) {
45
51
  for (const host of windowsHosts) {
46
52
  const win = host.windows;
47
53
  hosts[host.name] = {
48
- "configuration.winget": generateConfiguration(host.name, win, resolvedLock),
54
+ "configuration.winget": generateConfiguration(host.name, win, resolvedLock, configDir),
49
55
  "apply.ps1": generateApplyScript(),
50
56
  };
51
57
  }
@@ -54,9 +60,48 @@ export function generateWindows(evaluatedHosts, lock = emptyWindowsLock()) {
54
60
  /**
55
61
  * Render the WinGet Configuration YAML document (DSC v3) for one host.
56
62
  */
57
- function generateConfiguration(hostName, win, lock) {
63
+ function generateConfiguration(hostName, win, lock, configDir) {
64
+ validateWindowsWslResources(win);
58
65
  const packages = sortedPackages(win.packages ?? {});
59
- const prepared = prepareWindowsDscResources(win.commands ?? [], win.dsc ?? []);
66
+ const resources = (win.dsc ?? []).map((resource) => {
67
+ const metadata = resource.winix;
68
+ if (metadata?.kind === "file") {
69
+ const properties = resolveWindowsFileProperties(resource, configDir, windowsSourcePath);
70
+ if (metadata.wslConfig && properties) {
71
+ properties.setScript += "\nWrite-Warning 'WSL configuration changed. Restart WSL manually when safe; Winix will not stop running distros.'";
72
+ }
73
+ return cloneDscResource(resource, properties);
74
+ }
75
+ if (metadata?.kind === "optional-features") {
76
+ return cloneDscResource(resource, optionalFeatureProperties(metadata.names, metadata.enabled));
77
+ }
78
+ if (metadata?.kind === "wsl-distro") {
79
+ const setupRefs = (win.dsc ?? [])
80
+ .filter((entry) => (entry.winix?.kind === "optional-features" && entry.winix.enabled &&
81
+ entry.winix.names.some((name) => WSL_FEATURES.includes(name.toLowerCase()))) ||
82
+ (entry.winix?.kind === "file" && entry.winix.wslConfig))
83
+ .map((entry) => ({ kind: "dsc", token: entry.token }));
84
+ const runtime = packages.find((pkg) => pkg.id.toLowerCase() === "microsoft.wsl");
85
+ return cloneDscResource(resource, wslDistroProperties(metadata.distro, lock.wslImages ?? {}, lock.wslRepositories ?? {}), [
86
+ ...setupRefs, { kind: "package", id: runtime.id }, ...(resource.dependsOn ?? []),
87
+ ]);
88
+ }
89
+ 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()) {
93
+ throw new Error(`PowerShell module "${module.name}" has no matching pin in winix-windows.lock. Run winix update --windows.`);
94
+ }
95
+ const dependencies = [...(resource.dependsOn ?? [])];
96
+ if (packages.some((pkg) => pkg.id === "Microsoft.PowerShell") &&
97
+ !dependencies.some((ref) => ref.kind === "package" && ref.id === "Microsoft.PowerShell")) {
98
+ dependencies.push({ kind: "package", id: "Microsoft.PowerShell" });
99
+ }
100
+ return cloneDscResource(resource, powerShellModuleProperties(module, pin), dependencies);
101
+ }
102
+ return resource;
103
+ });
104
+ const prepared = prepareWindowsDscResources(win.commands ?? [], resources);
60
105
  const commands = prepared.commands;
61
106
  const dscResources = prepared.dscResources;
62
107
  const lines = [];
@@ -89,6 +134,56 @@ function generateConfiguration(hostName, win, lock) {
89
134
  }
90
135
  return lines.join("\n") + "\n";
91
136
  }
137
+ const WSL_FEATURES = ["microsoft-windows-subsystem-linux", "virtualmachineplatform"];
138
+ export function validateWindowsWslResources(win) {
139
+ const features = new Map();
140
+ const names = new Set();
141
+ const locations = new Set();
142
+ let defaults = 0;
143
+ let configs = 0;
144
+ let distros = 0;
145
+ for (const resource of win.dsc ?? []) {
146
+ const metadata = resource.winix;
147
+ if (metadata?.kind === "optional-features") {
148
+ for (const name of metadata.names) {
149
+ const key = name.toLowerCase();
150
+ if (features.has(key) && features.get(key) !== metadata.enabled) {
151
+ throw new Error(`Conflicting desired state for Windows optional feature: ${name}`);
152
+ }
153
+ features.set(key, metadata.enabled);
154
+ }
155
+ }
156
+ else if (metadata?.kind === "wsl-distro") {
157
+ distros++;
158
+ const { distro } = metadata;
159
+ const name = distro.name.toLowerCase();
160
+ const location = (typeof distro.installLocation === "string"
161
+ ? win32.normalize(distro.installLocation)
162
+ : JSON.stringify({ ...distro.installLocation, path: win32.normalize(distro.installLocation.path ?? "") })).toLowerCase();
163
+ if (names.has(name))
164
+ throw new Error(`Duplicate WSL distro: ${distro.name}`);
165
+ if (locations.has(location))
166
+ throw new Error("WSL distros cannot share an installLocation");
167
+ names.add(name);
168
+ locations.add(location);
169
+ if (distro.default)
170
+ defaults++;
171
+ }
172
+ else if (metadata?.kind === "file" && metadata.wslConfig) {
173
+ configs++;
174
+ }
175
+ }
176
+ if (defaults > 1)
177
+ throw new Error("Only one WSL distro can be declared default per Windows host");
178
+ if (configs > 1)
179
+ throw new Error("Declare only one windows.wsl({ config }) per Windows host");
180
+ if (distros && !WSL_FEATURES.every((name) => features.get(name) === true)) {
181
+ throw new Error("WSL distro provisioning requires windows.wsl() or both required optional features enabled");
182
+ }
183
+ if (distros && !Object.values(win.packages ?? {}).some((pkg) => pkg.id.toLowerCase() === "microsoft.wsl")) {
184
+ throw new Error('WSL distro provisioning requires windows.package("Microsoft.WSL")');
185
+ }
186
+ }
92
187
  function prepareWindowsDscResources(commands, resources) {
93
188
  const envResolvedResources = resolveManagedEnvironmentReferences(resources);
94
189
  if (!envResolvedResources.some((resource) => resource.winix?.kind === "setting")) {
@@ -539,6 +634,3 @@ function yamlQuoted(value) {
539
634
  function yamlStringArray(values) {
540
635
  return `[${values.map((value) => yamlQuoted(value)).join(", ")}]`;
541
636
  }
542
- function psSingleQuoted(value) {
543
- return `'${value.replace(/'/g, "''")}'`;
544
- }
@@ -1,5 +1,7 @@
1
1
  import type { EvaluatedHost } from "../../evaluator/index.js";
2
- import type { WinPackage, WinPackageSource } from "../../types/index.js";
2
+ import type { WinPackage, WinPackageSource, WinPowerShellModule } from "../../types/index.js";
3
+ import { type WslArchitecture, type WindowsWslImageResolver } from "./wsl.js";
4
+ import { type WindowsLockWslRepository, type WindowsWslRepositoryResolver } from "./wsl-setup.js";
3
5
  export declare const WINDOWS_LOCKFILE_NAME = "winix-windows.lock";
4
6
  export declare const WINDOWS_LOCK_VERSION = 1;
5
7
  export interface WindowsLockPackage {
@@ -11,7 +13,25 @@ export interface WindowsLock {
11
13
  version: typeof WINDOWS_LOCK_VERSION;
12
14
  generatedAt: string;
13
15
  packages: Record<string, WindowsLockPackage>;
16
+ /** PowerShell module names are case-insensitive, stored as lowercase keys. */
17
+ modules?: Record<string, WindowsLockModule>;
18
+ wslImages?: Record<string, WindowsLockWslImage>;
19
+ wslRepositories?: Record<string, WindowsLockWslRepository>;
14
20
  }
21
+ export interface WindowsLockWslImage {
22
+ source: "nixos-wsl";
23
+ architecture: WslArchitecture;
24
+ version: string;
25
+ url: string;
26
+ sha256: string;
27
+ resolvedAt: string;
28
+ }
29
+ export interface WindowsLockModule {
30
+ repository: string;
31
+ version: string;
32
+ resolvedAt: string;
33
+ }
34
+ export type WindowsModuleVersionResolver = (name: string, repository: string) => string;
15
35
  export type WindowsPackageVersionResolver = (id: string, source: WinPackageSource) => string;
16
36
  export interface WindowsLockResolution {
17
37
  id: string;
@@ -33,3 +53,18 @@ export declare function resolveMissingWindowsLockEntries(lock: WindowsLock, eval
33
53
  export declare function resolveWindowsLockEntries(lock: WindowsLock, packages: Iterable<WinPackage>, resolveVersion: WindowsPackageVersionResolver, now?: Date): WindowsLockResolutionResult;
34
54
  export declare function windowsLockChanged(before: WindowsLock, after: WindowsLock): boolean;
35
55
  export declare function serializeWindowsLock(lock: WindowsLock): string;
56
+ export declare function collectWindowsModules(hosts: EvaluatedHost[]): Map<string, WinPowerShellModule>;
57
+ export declare function hasWindowsWslDistros(hosts: EvaluatedHost[]): boolean;
58
+ export declare function resolveWindowsWslImages(lock: WindowsLock, resolve: WindowsWslImageResolver, now?: Date, missingOnly?: boolean): {
59
+ lock: WindowsLock;
60
+ changed: boolean;
61
+ };
62
+ export declare function resolveWindowsWslRepositories(lock: WindowsLock, hosts: EvaluatedHost[], resolve: WindowsWslRepositoryResolver, now?: Date, missingOnly?: boolean): {
63
+ lock: WindowsLock;
64
+ changed: boolean;
65
+ };
66
+ export declare function resolveWindowsModuleLockEntries(lock: WindowsLock, modules: Iterable<WinPowerShellModule>, resolveVersion: WindowsModuleVersionResolver, now?: Date, missingOnly?: boolean): {
67
+ lock: WindowsLock;
68
+ resolutions: Omit<WindowsLockResolution, "source">[];
69
+ changed: boolean;
70
+ };