@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
@@ -3,6 +3,45 @@
3
3
  // MVP vertical slice: packages plus raw commands. Mirrors the shape and
4
4
  // naming of the `nixos.*` / `darwin.*` namespaces. Additional helpers
5
5
  // (env, path, file, dsc, wsl, programs) land in follow-up milestones.
6
+ import { resolve, win32, posix } from "node:path";
7
+ import { fileURLToPath } from "node:url";
8
+ import { powerShellLiteral as psSingleQuoted } from "./utils.js";
9
+ const KNOWN_FOLDERS = {
10
+ documents: "MyDocuments",
11
+ desktop: "Desktop",
12
+ localAppData: "LocalApplicationData",
13
+ appData: "ApplicationData",
14
+ userProfile: "UserProfile",
15
+ };
16
+ function knownFolder(folder, path = "") {
17
+ if (!Object.hasOwn(KNOWN_FOLDERS, folder)) {
18
+ throw new Error(`Unknown Windows known folder "${folder}"`);
19
+ }
20
+ if (typeof path !== "string" || win32.isAbsolute(path) || /^[a-z]:/i.test(path) ||
21
+ path.split(/[\\/]/).includes("..")) {
22
+ throw new Error("windows.knownFolder path must be relative and cannot contain '..'");
23
+ }
24
+ return { kind: "knownFolder", folder, path };
25
+ }
26
+ function validFilePath(value) {
27
+ if (typeof value === "string")
28
+ return value.length > 0;
29
+ if (!value || value.kind !== "knownFolder")
30
+ return false;
31
+ knownFolder(value.folder, value.path);
32
+ return true;
33
+ }
34
+ function filePathLabel(value) {
35
+ return typeof value === "string" ? value : `${value.folder}\\${value.path}`;
36
+ }
37
+ export function filePathExpression(value) {
38
+ if (typeof value === "string")
39
+ return `Expand-WinixPath ${psSingleQuoted(value)}`;
40
+ const folder = psSingleQuoted(KNOWN_FOLDERS[value.folder]);
41
+ return `& { $root = [Environment]::GetFolderPath(${folder}); ` +
42
+ `if ([string]::IsNullOrWhiteSpace($root)) { throw 'Windows known folder is unavailable: ${value.folder}' }; ` +
43
+ (value.path ? `Join-Path $root ${psSingleQuoted(value.path)}` : "$root") + " }";
44
+ }
6
45
  /**
7
46
  * Resolve `dependsOn` (a single handle or an array) into the stable resource
8
47
  * references the emitter wires up. Throws on a value that is not a Winix
@@ -64,8 +103,8 @@ function normalizeRawCommand(arg) {
64
103
  throw new Error("windows.raw(command) requires a non-empty command string");
65
104
  }
66
105
  return withToken({
67
- executable: "powershell",
68
- arguments: ["-Command", arg],
106
+ executable: "pwsh",
107
+ arguments: ["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", arg],
69
108
  });
70
109
  }
71
110
  if (!arg || typeof arg !== "object") {
@@ -128,7 +167,7 @@ function withDscMetadata(resource, metadata) {
128
167
  return resource;
129
168
  }
130
169
  const REGISTRY_RESOURCE = "Microsoft.Windows/Registry";
131
- const WINDOWS_POWERSHELL_SCRIPT_RESOURCE = "Microsoft.DSC.Transitional/WindowsPowerShellScript";
170
+ const POWERSHELL_SCRIPT_RESOURCE = "Microsoft.DSC.Transitional/PowerShellScript";
132
171
  const WINDOWS_SETTINGS_RESOURCE = "Microsoft.Windows.Settings/WindowsSettings";
133
172
  const USER_ENV_KEY_PATH = "HKCU\\Environment";
134
173
  const MACHINE_ENV_KEY_PATH = "HKLM\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment";
@@ -341,7 +380,7 @@ function normalizePath(value, ensure, opts) {
341
380
  }
342
381
  const scope = envScope(normalizedOpts);
343
382
  const resource = {
344
- resourceType: WINDOWS_POWERSHELL_SCRIPT_RESOURCE,
383
+ resourceType: POWERSHELL_SCRIPT_RESOURCE,
345
384
  name: `${ensure === "Present" ? "Add" : "Remove"} ${value} ${ensure === "Present" ? "to" : "from"} PATH`,
346
385
  properties: buildPathScriptProperties({
347
386
  dir: value,
@@ -378,9 +417,9 @@ function normalizeFileOpts(opts, helper) {
378
417
  }
379
418
  return opts;
380
419
  }
381
- function fileDsc(name, properties, opts) {
420
+ function scriptDsc(name, properties, opts) {
382
421
  const resource = {
383
- resourceType: WINDOWS_POWERSHELL_SCRIPT_RESOURCE,
422
+ resourceType: POWERSHELL_SCRIPT_RESOURCE,
384
423
  name,
385
424
  properties,
386
425
  };
@@ -393,58 +432,96 @@ function fileDsc(name, properties, opts) {
393
432
  }
394
433
  function normalizeFileText(target, content, opts) {
395
434
  const normalizedOpts = normalizeFileOpts(opts, "windows.file.text");
396
- if (!target || typeof target !== "string") {
435
+ if (!validFilePath(target)) {
397
436
  throw new Error("windows.file.text(target) requires a non-empty target path");
398
437
  }
399
438
  if (typeof content !== "string") {
400
439
  throw new Error("windows.file.text(target, content) requires string content");
401
440
  }
402
441
  const encoding = normalizedOpts.encoding ?? "utf8";
403
- return fileDsc(`Write file ${target}`, buildFileTextScriptProperties({
442
+ return withFileMetadata(scriptDsc(`Write file ${filePathLabel(target)}`, buildFileTextScriptProperties({
404
443
  target,
405
444
  content,
406
445
  encoding,
407
446
  force: normalizedOpts.force ?? false,
408
447
  backup: normalizedOpts.backup ?? false,
409
- }), normalizedOpts);
448
+ }), normalizedOpts), "text", target, normalizedOpts, undefined, content);
410
449
  }
411
450
  function normalizeFileSymlink(target, source, opts) {
412
451
  const normalizedOpts = normalizeFileOpts(opts, "windows.file.symlink");
413
- if (!target || typeof target !== "string") {
452
+ if (!validFilePath(target)) {
414
453
  throw new Error("windows.file.symlink(target) requires a non-empty target path");
415
454
  }
455
+ source = source instanceof URL ? fileURLToPath(source) : source;
416
456
  if (!source || typeof source !== "string") {
417
457
  throw new Error("windows.file.symlink(target, source) requires a non-empty source path");
418
458
  }
419
- return fileDsc(`Link file ${target}`, buildFileSymlinkScriptProperties({
459
+ return withFileMetadata(scriptDsc(`Link file ${filePathLabel(target)}`, buildFileSymlinkScriptProperties({
420
460
  target,
421
461
  source,
422
462
  recursive: normalizedOpts.recursive ?? false,
423
463
  force: normalizedOpts.force ?? false,
424
464
  backup: normalizedOpts.backup ?? false,
425
- }), normalizedOpts);
465
+ }), normalizedOpts), "symlink", target, normalizedOpts, source);
426
466
  }
427
467
  function normalizeFileCopy(target, source, opts) {
428
468
  const normalizedOpts = normalizeFileOpts(opts, "windows.file.copy");
429
- if (!target || typeof target !== "string") {
469
+ if (!validFilePath(target)) {
430
470
  throw new Error("windows.file.copy(target) requires a non-empty target path");
431
471
  }
472
+ source = source instanceof URL ? fileURLToPath(source) : source;
432
473
  if (!source || typeof source !== "string") {
433
474
  throw new Error("windows.file.copy(target, source) requires a non-empty source path");
434
475
  }
435
- return fileDsc(`Copy file ${target}`, buildFileCopyScriptProperties({
476
+ return withFileMetadata(scriptDsc(`Copy file ${filePathLabel(target)}`, buildFileCopyScriptProperties({
436
477
  target,
437
478
  source,
438
479
  force: normalizedOpts.force ?? false,
439
480
  backup: normalizedOpts.backup ?? false,
440
- }), normalizedOpts);
481
+ }), normalizedOpts), "copy", target, normalizedOpts, source);
441
482
  }
442
483
  function normalizeFileRemove(target, opts) {
443
484
  const normalizedOpts = normalizeFileOpts(opts, "windows.file.remove");
444
- if (!target || typeof target !== "string") {
485
+ if (!validFilePath(target)) {
445
486
  throw new Error("windows.file.remove(target) requires a non-empty target path");
446
487
  }
447
- return fileDsc(`Remove file ${target}`, buildFileRemoveScriptProperties({ target }), normalizedOpts);
488
+ return withFileMetadata(scriptDsc(`Remove file ${filePathLabel(target)}`, buildFileRemoveScriptProperties({ target }), normalizedOpts), "remove", target, normalizedOpts);
489
+ }
490
+ function withFileMetadata(resource, action, target, opts, source, content) {
491
+ return withDscMetadata(resource, {
492
+ kind: "file", action, target, source, content,
493
+ encoding: opts.encoding ?? "utf8",
494
+ force: opts.force ?? false,
495
+ backup: opts.backup ?? false,
496
+ recursive: opts.recursive ?? false,
497
+ });
498
+ }
499
+ /** Rebuild scripts after the emitter supplies the config directory. */
500
+ export function resolveWindowsFileProperties(resource, configDir, sourcePath = (path) => path) {
501
+ const file = resource.winix;
502
+ if (file?.kind !== "file")
503
+ return resource.properties;
504
+ let source = file.source;
505
+ if (source !== undefined && !/%[^%]+%/.test(source) &&
506
+ !win32.isAbsolute(source) && !posix.isAbsolute(source)) {
507
+ if (!configDir)
508
+ throw new Error("Relative Windows file sources require a configDir when calling generateWindows.");
509
+ if (/^[a-z]:/i.test(source))
510
+ throw new Error(`Drive-relative Windows source is ambiguous: ${source}`);
511
+ source = /^[a-z]:[\\/]|^[\\/]{2}/i.test(configDir)
512
+ ? win32.resolve(configDir, source)
513
+ : posix.isAbsolute(configDir)
514
+ ? posix.resolve(configDir, source.replaceAll("\\", "/"))
515
+ : resolve(configDir, source);
516
+ }
517
+ if (source !== undefined && !/%[^%]+%/.test(source))
518
+ source = sourcePath(source);
519
+ switch (file.action) {
520
+ case "text": return buildFileTextScriptProperties({ ...file, content: file.content });
521
+ case "remove": return buildFileRemoveScriptProperties(file);
522
+ case "symlink": return buildFileSymlinkScriptProperties({ ...file, source: source });
523
+ case "copy": return buildFileCopyScriptProperties({ ...file, source: source });
524
+ }
448
525
  }
449
526
  function buildPathScriptProperties(opts) {
450
527
  const registryPath = envRegistryPath(opts.scope);
@@ -499,7 +576,7 @@ function buildPathScriptProperties(opts) {
499
576
  }
500
577
  function buildFileTextScriptProperties(opts) {
501
578
  const vars = [
502
- `$target = Expand-WinixPath ${psSingleQuoted(opts.target)}`,
579
+ `$target = ${filePathExpression(opts.target)}`,
503
580
  `$content = ${psSingleQuoted(opts.content)}`,
504
581
  `$encoding = ${psSingleQuoted(opts.encoding)}`,
505
582
  `$force = ${psBoolean(opts.force)}`,
@@ -508,7 +585,7 @@ function buildFileTextScriptProperties(opts) {
508
585
  return {
509
586
  getScript: [
510
587
  ...filePathPrelude(),
511
- `$target = Expand-WinixPath ${psSingleQuoted(opts.target)}`,
588
+ `$target = ${filePathExpression(opts.target)}`,
512
589
  "if (Test-Path -LiteralPath $target -PathType Leaf) { [IO.File]::ReadAllText($target) } else { '' }",
513
590
  ].join("\n"),
514
591
  testScript: [
@@ -544,7 +621,7 @@ function buildFileSymlinkScriptProperties(opts) {
544
621
  return {
545
622
  getScript: [
546
623
  ...fileSymlinkPrelude(),
547
- `$target = Expand-WinixPath ${psSingleQuoted(opts.target)}`,
624
+ `$target = ${filePathExpression(opts.target)}`,
548
625
  "if (Test-Path -LiteralPath $target) { (Get-Item -LiteralPath $target -Force).LinkType } else { '' }",
549
626
  ].join("\n"),
550
627
  testScript: [
@@ -575,7 +652,7 @@ function buildFileCopyScriptProperties(opts) {
575
652
  return {
576
653
  getScript: [
577
654
  ...filePathPrelude(),
578
- `$target = Expand-WinixPath ${psSingleQuoted(opts.target)}`,
655
+ `$target = ${filePathExpression(opts.target)}`,
579
656
  "if (Test-Path -LiteralPath $target) { $target } else { '' }",
580
657
  ].join("\n"),
581
658
  testScript: [
@@ -603,17 +680,17 @@ function buildFileRemoveScriptProperties(opts) {
603
680
  return {
604
681
  getScript: [
605
682
  ...filePathPrelude(),
606
- `$target = Expand-WinixPath ${psSingleQuoted(opts.target)}`,
683
+ `$target = ${filePathExpression(opts.target)}`,
607
684
  "if (Test-Path -LiteralPath $target) { $target } else { '' }",
608
685
  ].join("\n"),
609
686
  testScript: [
610
687
  ...filePathPrelude(),
611
- `$target = Expand-WinixPath ${psSingleQuoted(opts.target)}`,
688
+ `$target = ${filePathExpression(opts.target)}`,
612
689
  "-not (Test-Path -LiteralPath $target)",
613
690
  ].join("\n"),
614
691
  setScript: [
615
692
  ...filePathPrelude(),
616
- `$target = Expand-WinixPath ${psSingleQuoted(opts.target)}`,
693
+ `$target = ${filePathExpression(opts.target)}`,
617
694
  "if (-not (Test-Path -LiteralPath $target)) { return }",
618
695
  "$item = Get-Item -LiteralPath $target -Force",
619
696
  "if ($item.PSIsContainer -and $null -eq $item.LinkType) {",
@@ -626,9 +703,9 @@ function buildFileRemoveScriptProperties(opts) {
626
703
  function fileScriptVars(values) {
627
704
  return Object.entries(values).map(([name, value]) => typeof value === "boolean"
628
705
  ? `$${name} = ${psBoolean(value)}`
629
- : `$${name} = Expand-WinixPath ${psSingleQuoted(value)}`);
706
+ : `$${name} = ${filePathExpression(value)}`);
630
707
  }
631
- function filePathPrelude() {
708
+ export function filePathPrelude() {
632
709
  return [
633
710
  "function Expand-WinixPath([string]$Path) { [Environment]::ExpandEnvironmentVariables($Path) }",
634
711
  ];
@@ -768,8 +845,102 @@ function fileCopyPrelude() {
768
845
  function psBoolean(value) {
769
846
  return value ? "$true" : "$false";
770
847
  }
771
- function psSingleQuoted(value) {
772
- return `'${value.replace(/'/g, "''")}'`;
848
+ function normalizeStartupCommand(name, spec) {
849
+ const helper = "windows.startup.command";
850
+ if (typeof name !== "string" || !name.trim() || /[<>:"/\\|?*\x00-\x1f]|[. ]$/.test(name) ||
851
+ /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(name) || name.length > 251) {
852
+ throw new Error(`${helper} requires a valid shortcut name without path separators or reserved Windows names`);
853
+ }
854
+ if (!spec || typeof spec !== "object" || Array.isArray(spec)) {
855
+ throw new Error(`${helper} requires a command specification`);
856
+ }
857
+ normalizeFileOpts(spec, helper);
858
+ for (const [key, value] of [
859
+ ["executable", spec.executable],
860
+ ["workingDirectory", spec.workingDirectory ?? knownFolder("userProfile")],
861
+ ]) {
862
+ if (!validFilePath(value) || /\0/.test(filePathLabel(value))) {
863
+ throw new Error(`${helper} ${key} requires a non-empty path or application name`);
864
+ }
865
+ }
866
+ if (spec.arguments !== undefined && (!Array.isArray(spec.arguments) || spec.arguments.some((value) => (typeof value !== "string" && !validFilePath(value)) || /\0/.test(filePathLabel(value))))) {
867
+ throw new Error(`${helper} arguments must be strings or known-folder paths without null characters`);
868
+ }
869
+ const styles = { normal: 1, minimized: 7, maximized: 3 };
870
+ const style = spec.windowStyle ?? "normal";
871
+ if (!Object.hasOwn(styles, style)) {
872
+ throw new Error(`${helper} windowStyle must be normal, minimized, or maximized`);
873
+ }
874
+ const args = (spec.arguments ?? []).map((value) => typeof value === "string" ? psSingleQuoted(value) : `(${filePathExpression(value)})`);
875
+ const prelude = [
876
+ "$ErrorActionPreference = 'Stop'",
877
+ ...filePathPrelude(),
878
+ ...fileMoveTargetPrelude(),
879
+ String.raw `function ConvertTo-WinixArgument([string]$Value) {
880
+ if ($Value.Length -gt 0 -and $Value -notmatch '[\s"]') { return $Value }
881
+ $escaped = [regex]::Replace($Value, '(\\*)"', '$1$1\"')
882
+ $escaped = [regex]::Replace($escaped, '(\\+)$', '$1$1')
883
+ return '"' + $escaped + '"'
884
+ }`,
885
+ "$startup = [Environment]::GetFolderPath('Startup')",
886
+ "if ([string]::IsNullOrWhiteSpace($startup)) { throw 'Windows Startup folder is unavailable' }",
887
+ `$target = Join-Path $startup ${psSingleQuoted(`${name}.lnk`)}`,
888
+ `$executable = ${filePathExpression(spec.executable)}`,
889
+ String.raw `if ($executable -notmatch '[/\\:]') {`,
890
+ " $commands = @(Get-Command -Name $executable -CommandType Application -ErrorAction Stop)",
891
+ " if ($commands.Count -ne 1) { throw \"Startup application name is ambiguous: $executable\" }",
892
+ " $executable = $commands[0].Source",
893
+ "}",
894
+ "if (-not [IO.Path]::IsPathFullyQualified($executable)) { throw \"Startup executable must be an absolute path or application name: $executable\" }",
895
+ "if (-not (Test-Path -LiteralPath $executable -PathType Leaf)) { throw \"Startup executable is missing: $executable\" }",
896
+ "$executable = (Resolve-Path -LiteralPath $executable).ProviderPath",
897
+ `$workingDirectory = ${filePathExpression(spec.workingDirectory ?? knownFolder("userProfile"))}`,
898
+ "if (-not [IO.Path]::IsPathFullyQualified($workingDirectory) -or -not (Test-Path -LiteralPath $workingDirectory -PathType Container)) { throw \"Startup working directory must be an existing absolute directory: $workingDirectory\" }",
899
+ "$workingDirectory = (Resolve-Path -LiteralPath $workingDirectory).ProviderPath",
900
+ `$arguments = (@(${args.join(", ")}) | ForEach-Object { ConvertTo-WinixArgument $_ }) -join ' '`,
901
+ `$windowStyle = ${styles[style]}`,
902
+ // WScript.Shell uses ANSI for shortcut arguments; Shell.Application preserves Unicode.
903
+ "$shell = New-Object -ComObject Shell.Application",
904
+ "function Get-WinixStartupLink([string]$Path) {",
905
+ " $folder = $shell.NameSpace((Split-Path -Parent $Path))",
906
+ " if ($null -eq $folder) { throw \"Unable to read shortcut directory: $Path\" }",
907
+ " $item = $folder.ParseName((Split-Path -Leaf $Path))",
908
+ " if ($null -eq $item) { throw \"Unable to read shortcut: $Path\" }",
909
+ " return $item.GetLink()",
910
+ "}",
911
+ "function Test-WinixStartup([string]$Path = $target) {",
912
+ " if (-not (Test-Path -LiteralPath $Path -PathType Leaf)) { return $false }",
913
+ " $link = Get-WinixStartupLink $Path",
914
+ " return $link.Path -ieq $executable -and $link.Arguments -ceq $arguments -and $link.WorkingDirectory -ieq $workingDirectory -and $link.ShowCommand -eq $windowStyle",
915
+ "}",
916
+ ];
917
+ return withDscMetadata(scriptDsc(`Startup ${name}`, {
918
+ getScript: [...prelude, "@{ Path = $target; InDesiredState = (Test-WinixStartup) }"].join("\n"),
919
+ testScript: [...prelude, "Test-WinixStartup"].join("\n"),
920
+ setScript: [
921
+ ...prelude,
922
+ "if (Test-WinixStartup) { return }",
923
+ "$stagingDirectory = Join-Path ([IO.Path]::GetTempPath()) ('winix-startup-' + [guid]::NewGuid().ToString('N'))",
924
+ "[IO.Directory]::CreateDirectory($stagingDirectory) | Out-Null",
925
+ "try {",
926
+ " $stagingPath = Join-Path $stagingDirectory 'shortcut.lnk'",
927
+ " $seed = (New-Object -ComObject WScript.Shell).CreateShortcut($stagingPath)",
928
+ " $seed.TargetPath = $env:ComSpec",
929
+ " $seed.Save()",
930
+ " $link = Get-WinixStartupLink $stagingPath",
931
+ " $link.Path = $executable",
932
+ " $link.Arguments = $arguments",
933
+ " $link.WorkingDirectory = $workingDirectory",
934
+ " $link.ShowCommand = $windowStyle",
935
+ " $link.Save()",
936
+ " if (-not (Test-WinixStartup $stagingPath)) { throw \"Startup shortcut verification failed: $stagingPath\" }",
937
+ " [IO.Directory]::CreateDirectory($startup) | Out-Null",
938
+ ` Move-WinixExistingTarget $target ${psBoolean(spec.force ?? false)} ${psBoolean(spec.backup ?? false)}`,
939
+ " Move-Item -LiteralPath $stagingPath -Destination $target",
940
+ "} finally { Remove-Item -LiteralPath $stagingDirectory -Recurse -Force }",
941
+ "if (-not (Test-WinixStartup)) { throw \"Startup shortcut verification failed: $target\" }",
942
+ ].join("\n"),
943
+ }, spec), { kind: "startup", name });
773
944
  }
774
945
  /**
775
946
  * Attach a resource identity to a fragment, turning it into a handle that can
@@ -789,6 +960,74 @@ function dscHandle(resource) {
789
960
  return asHandle(fragment, { kind: "dsc", token: resource.token });
790
961
  }
791
962
  export const windows = {
963
+ optionalFeature: (name, opts = {}) => optionalFeatures([name], opts),
964
+ wsl: Object.assign((opts = {}) => {
965
+ normalizeFileOpts(opts, "windows.wsl");
966
+ const content = opts.config === undefined ? undefined : serializeWslConfig(opts.config);
967
+ const enabled = optionalFeatures(["Microsoft-Windows-Subsystem-Linux", "VirtualMachinePlatform"], { dependsOn: opts.dependsOn });
968
+ if (content === undefined)
969
+ return enabled;
970
+ const resource = normalizeFileText(knownFolder("userProfile", ".wslconfig"), content, {
971
+ backup: opts.backup, force: opts.force, dependsOn: opts.dependsOn,
972
+ });
973
+ if (resource.winix?.kind === "file")
974
+ resource.winix.wslConfig = true;
975
+ resource.name = "WSL configuration";
976
+ resource.dependsOn = [enabled.__winixHandle, ...(resource.dependsOn ?? [])];
977
+ const configured = dscHandle(resource);
978
+ configured.windows.dsc.unshift(...enabled.windows.dsc);
979
+ return configured;
980
+ }, {
981
+ distro: (name, spec) => {
982
+ if (typeof name !== "string" || !/^[a-z0-9][a-z0-9._-]{0,63}$/i.test(name)) {
983
+ throw new Error("windows.wsl.distro requires a distro name containing only letters, numbers, '.', '_' or '-'");
984
+ }
985
+ if (!spec || spec.source !== "nixos-wsl" || !validFilePath(spec.installLocation) ||
986
+ (typeof spec.installLocation === "string" &&
987
+ (!win32.isAbsolute(spec.installLocation) && !spec.installLocation.startsWith("%"))) ||
988
+ (spec.default !== undefined && typeof spec.default !== "boolean")) {
989
+ throw new Error("windows.wsl.distro requires source 'nixos-wsl', an absolute/environment/known-folder installLocation, and an optional boolean default");
990
+ }
991
+ return dscHandle(withDscMetadata(withDscToken({
992
+ resourceType: POWERSHELL_SCRIPT_RESOURCE,
993
+ name: `WSL distro ${name}`,
994
+ dependsOn: resolveDependsOn(spec.dependsOn),
995
+ }), { kind: "wsl-distro", distro: {
996
+ name, source: spec.source, installLocation: spec.installLocation, default: spec.default ?? false,
997
+ ...(spec.setup === undefined ? {} : { setup: normalizeWslSetup(spec.setup) }),
998
+ } }));
999
+ },
1000
+ }),
1001
+ startup: {
1002
+ command: (name, spec) => dscHandle(normalizeStartupCommand(name, spec)),
1003
+ },
1004
+ knownFolder: {
1005
+ documents: (path) => knownFolder("documents", path),
1006
+ desktop: (path) => knownFolder("desktop", path),
1007
+ localAppData: (path) => knownFolder("localAppData", path),
1008
+ appData: (path) => knownFolder("appData", path),
1009
+ userProfile: (path) => knownFolder("userProfile", path),
1010
+ },
1011
+ powershell: {
1012
+ module: (name, opts = {}) => {
1013
+ if (typeof name !== "string" || !/^[a-z0-9][a-z0-9._-]*$/i.test(name)) {
1014
+ throw new Error("windows.powershell.module requires a module name without wildcards or paths");
1015
+ }
1016
+ if (!opts || typeof opts !== "object" || Array.isArray(opts)) {
1017
+ throw new Error("windows.powershell.module options must be an object");
1018
+ }
1019
+ const repository = opts.repository ?? "PSGallery";
1020
+ if (typeof repository !== "string" || !/^[a-z0-9][a-z0-9._-]*$/i.test(repository)) {
1021
+ throw new Error("windows.powershell.module repository must be a registered repository name");
1022
+ }
1023
+ const resource = withDscMetadata(withDscToken({
1024
+ resourceType: POWERSHELL_SCRIPT_RESOURCE,
1025
+ name: `PowerShell module ${name}`,
1026
+ dependsOn: resolveDependsOn(opts.dependsOn),
1027
+ }), { kind: "powershell-module", module: { name, repository } });
1028
+ return dscHandle(resource);
1029
+ },
1030
+ },
792
1031
  package: (arg) => {
793
1032
  const pkg = normalizePackage(arg);
794
1033
  const fragment = { windows: { packages: { [pkg.id]: pkg } } };
@@ -820,3 +1059,87 @@ export const windows = {
820
1059
  remove: (target, opts) => dscHandle(normalizeFileRemove(target, opts)),
821
1060
  },
822
1061
  };
1062
+ export function normalizeWslSetup(setup) {
1063
+ if (!setup || typeof setup !== "object" || Array.isArray(setup)) {
1064
+ throw new Error("windows.wsl.distro setup must be an object");
1065
+ }
1066
+ let url;
1067
+ try {
1068
+ url = new URL(setup.repository);
1069
+ }
1070
+ catch {
1071
+ throw new Error("WSL setup repository must be an HTTPS Git URL");
1072
+ }
1073
+ if (url.protocol !== "https:" || url.username || url.password || url.search || url.hash) {
1074
+ throw new Error("WSL setup repository must be HTTPS without credentials, query, or fragment");
1075
+ }
1076
+ const ref = setup.ref ?? "HEAD";
1077
+ if (typeof ref !== "string" || !/^[a-z0-9][a-z0-9._/-]*$/i.test(ref) || ref.includes("..") ||
1078
+ ref.endsWith("/") || ref.includes("//"))
1079
+ throw new Error("Invalid WSL setup Git ref");
1080
+ if (typeof setup.configDirectory !== "string" || !setup.configDirectory ||
1081
+ setup.configDirectory.startsWith("/") || /^[a-z]:/i.test(setup.configDirectory) || /[\\\x00-\x1f\x7f]/.test(setup.configDirectory) ||
1082
+ setup.configDirectory.split("/").includes(".."))
1083
+ throw new Error("WSL setup configDirectory must stay inside the repository");
1084
+ if (typeof setup.host !== "string" || !/^[a-z0-9][a-z0-9._-]*$/i.test(setup.host))
1085
+ throw new Error("Invalid WSL setup host");
1086
+ if (setup.user !== undefined && (typeof setup.user !== "string" ||
1087
+ !/^[a-z_][a-z0-9_-]*$/.test(setup.user) || setup.user === "root"))
1088
+ throw new Error("WSL setup user must be a non-root Linux account");
1089
+ if (setup.checkout !== undefined && (typeof setup.checkout !== "string" || !setup.checkout.startsWith("/") ||
1090
+ /^\/+$/.test(setup.checkout) || /[\\\x00-\x1f\x7f]/.test(setup.checkout) ||
1091
+ setup.checkout.split("/").some((part) => part === ".." || part === ".")))
1092
+ throw new Error("WSL setup checkout must be an absolute Linux directory");
1093
+ return {
1094
+ repository: url.href, ref, configDirectory: posix.normalize(setup.configDirectory), host: setup.host,
1095
+ ...(setup.checkout === undefined ? {} : { checkout: posix.normalize(setup.checkout).replace(/\/+$/, "") }),
1096
+ ...(setup.user === undefined ? {} : { user: setup.user }),
1097
+ };
1098
+ }
1099
+ function optionalFeatures(names, opts) {
1100
+ if (!opts || typeof opts !== "object" || Array.isArray(opts) ||
1101
+ (opts.enabled !== undefined && typeof opts.enabled !== "boolean") ||
1102
+ names.some((name) => typeof name !== "string" || !/^[a-z0-9][a-z0-9._-]*$/i.test(name))) {
1103
+ throw new Error("windows.optionalFeature requires a Windows feature name and boolean enabled option");
1104
+ }
1105
+ return dscHandle(withDscMetadata(withDscToken({
1106
+ resourceType: POWERSHELL_SCRIPT_RESOURCE,
1107
+ name: `Windows features ${names.join(" ")}`,
1108
+ elevated: true,
1109
+ dependsOn: resolveDependsOn(opts.dependsOn),
1110
+ }), { kind: "optional-features", names, enabled: opts.enabled ?? true }));
1111
+ }
1112
+ function serializeWslConfig(config) {
1113
+ const allowed = {
1114
+ wsl2: {
1115
+ memory: "positive-size", swap: "size", processors: "integer",
1116
+ localhostForwarding: "boolean", dnsTunneling: "boolean", firewall: "boolean",
1117
+ autoProxy: "boolean", guiApplications: "boolean",
1118
+ networkingMode: ["nat", "mirrored", "none", "virtioproxy"],
1119
+ },
1120
+ experimental: { autoMemoryReclaim: ["disabled", "gradual", "dropCache"], sparseVhd: "boolean" },
1121
+ };
1122
+ if (!config || typeof config !== "object" || Array.isArray(config) || !Object.keys(config).length) {
1123
+ throw new Error("windows.wsl config must be a non-empty configuration object");
1124
+ }
1125
+ const lines = [];
1126
+ for (const [section, entries] of Object.entries(config)) {
1127
+ if (!Object.hasOwn(allowed, section) || !entries || typeof entries !== "object" ||
1128
+ Array.isArray(entries) || !Object.keys(entries).length)
1129
+ throw new Error(`Invalid .wslconfig section: ${section}`);
1130
+ lines.push(`[${section}]`);
1131
+ for (const [key, value] of Object.entries(entries)) {
1132
+ const rule = allowed[section][key];
1133
+ const valid = Array.isArray(rule) ? rule.includes(value) :
1134
+ rule === "boolean" ? typeof value === "boolean" :
1135
+ rule === "integer" ? typeof value === "number" && Number.isSafeInteger(value) && value > 0 :
1136
+ rule === "positive-size" ? typeof value === "string" && /^[1-9]\d*(?:MB|GB)$/i.test(value) :
1137
+ rule === "size" ? typeof value === "string" && /^(?:0|(?:0|[1-9]\d*)(?:MB|GB))$/i.test(value) : false;
1138
+ if (!valid)
1139
+ throw new Error(`Invalid .wslconfig option: ${section}.${key}`);
1140
+ lines.push(`${key}=${String(value)}`);
1141
+ }
1142
+ lines.push("");
1143
+ }
1144
+ return lines.join("\n");
1145
+ }
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- export type { Fragment, FragmentFactory, PlatformFactory, ProfileFactory, LazyFragment, PlatformLazyFragment, FragmentEntry, FragmentResult, NixExpr, RawModuleRef, ImportRef, InputDef, InputWithOptions, WorkspaceDef, HostDef, EvalContext } from "./core/types.js";
2
- export type { Attrs, BootOptions, DarwinNetworking, DarwinOptions, DarwinSecurity, DarwinDefaults, DarwinSystem, EnvironmentOptions, FirewallOptions, FontsOptions, FzfOptions, GitInclude, GitOptions, HomeActivation, HomebrewOptions, HomeConfig, HomeFile, HomeOptions, I18nOptions, LaunchdAgentOptions, LaunchdOptions, NeovimOptions, NetworkingOptions, NixConfig, NixGcOptions, NixHomebrewOptions, NixOptions, NixpkgsOptions, NixosSecurityOptions, NixosSystemOptions, NixPrimitive, NixSettings, NixValue, NixosOptions, OciContainerOptions, PackageRef, Script, ServicesOptions, StarshipOptions, SystemdOptions, SystemdService, SystemdTimer, TimeOptions, TmuxOptions, UserOptions, UsersOptions, VirtualisationOptions, WslOptions, XdgFile, XdgOptions, ZoxideOptions, ZshOptions, WindowsOptions, WinPackage, WinPackageSource, WinRawCommand, WinSettings, WinColorMode, WinStartFolder, WinTaskbarAlignment, WinTaskbarGroupingMode, WinTaskbarMultiMonMode, } from "./types/index.js";
1
+ export type { Fragment, ResourceHandle, FragmentFactory, PlatformFactory, ProfileFactory, LazyFragment, PlatformLazyFragment, FragmentEntry, FragmentResult, NixExpr, RawModuleRef, ImportRef, InputDef, InputWithOptions, WorkspaceDef, HostDef, EvalContext } from "./core/types.js";
2
+ export type { Attrs, BootOptions, DarwinNetworking, DarwinOptions, DarwinSecurity, DarwinDefaults, DarwinSystem, EnvironmentOptions, FirewallOptions, FontsOptions, FzfOptions, GitInclude, GitOptions, HomeActivation, HomebrewOptions, HomeConfig, HomeFile, HomeOptions, I18nOptions, LaunchdAgentOptions, LaunchdOptions, NeovimOptions, NetworkingOptions, NixConfig, NixGcOptions, NixHomebrewOptions, NixOptions, NixpkgsOptions, NixosSecurityOptions, NixosSystemOptions, NixPrimitive, NixSettings, NixValue, NixosOptions, OciContainerOptions, PackageRef, Script, ServicesOptions, StarshipOptions, SystemdOptions, SystemdService, SystemdTimer, TimeOptions, TmuxOptions, UserOptions, UsersOptions, VirtualisationOptions, WslOptions, XdgFile, XdgOptions, ZoxideOptions, ZshOptions, WindowsOptions, WinPackage, WinPackageSource, WinRawCommand, WinSettings, WinColorMode, WinStartFolder, WinTaskbarAlignment, WinTaskbarGroupingMode, WinTaskbarMultiMonMode, WinKnownFolder, WinKnownFolderName, WinFilePath, WinPowerShellModule, WinStartupCommand, WinStartupWindowStyle, } from "./types/index.js";
3
3
  export { platform, feature, profile, host, workspace, input, defineInputs, rawModule, withContext } from "./sdk/index.js";
4
4
  export type { WinixContext } from "./sdk/context.js";
5
5
  export { evaluate } from "./evaluator/index.js";
@@ -9,4 +9,6 @@ export type { NixOutput } from "./backends/nix/index.js";
9
9
  export { generateWindows, isWindowsHost } from "./backends/windows/index.js";
10
10
  export type { WindowsOutput, WindowsHostOutput } from "./backends/windows/index.js";
11
11
  export { account, darwin, home, nix, nixos, overlay, platforms, windows } from "./helpers/index.js";
12
+ export type { WinPowerShellModuleOpts, WinStartupCommandSpec, WinStartupNamespace, WinOptionalFeatureOpts, WinWslDistroSpec, WinWslOpts, WinWslNamespace } from "./helpers/index.js";
13
+ export type { WinWslConfig, WinWslDistro, WinWslSetup } from "./types/index.js";
12
14
  export type { AccountGroupFactory, AccountGroupMember, AccountGroupOpts, AccountNamespace, AccountOpts, AccountUserFactory, AccountUserRef, ActivationOpts, BinaryReleaseArch, BinaryReleaseCompletions, BinaryReleaseFormat, BinaryReleaseMeta, BinaryReleaseOpts, BinaryReleasePlatform, DarwinHelper, DarwinPlatformOpts, DarwinProgramOptions, DarwinServiceOptions, HomeHelper, HomeProgramOptions, HomeServiceOptions, LaunchdHelper, NixNamespace, NixosHelper, NixosPlatformOpts, NixosProgramOptions, NixosServiceOptions, OverlayHelper, PkgHelper, PlatformsHelper, ScriptHelper, SysctlSettings, SystemdHelper, VirtualisationHelper, WindowsHelper, WindowsPlatformOpts, WinEnvNamespace, WinEnvOpts, WinEnvScope, WinFileEncoding, WinFileNamespace, WinFileOpts, WinPackageArg, WinPackageSpec, WinPathNamespace, WinRawCommandArg, WinRawCommandSpec, WinSettingOpts } from "./helpers/index.js";