@adrifer/winix 0.2.0-preview.4 → 0.2.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.
@@ -118,8 +118,18 @@ function withDscToken(resource) {
118
118
  });
119
119
  return resource;
120
120
  }
121
+ /** Stamp internal typed-helper metadata without affecting public equality/YAML. */
122
+ function withDscMetadata(resource, metadata) {
123
+ Object.defineProperty(resource, "winix", {
124
+ value: metadata,
125
+ enumerable: false,
126
+ configurable: true,
127
+ });
128
+ return resource;
129
+ }
121
130
  const REGISTRY_RESOURCE = "Microsoft.Windows/Registry";
122
131
  const WINDOWS_POWERSHELL_SCRIPT_RESOURCE = "Microsoft.DSC.Transitional/WindowsPowerShellScript";
132
+ const WINDOWS_SETTINGS_RESOURCE = "Microsoft.Windows.Settings/WindowsSettings";
123
133
  const USER_ENV_KEY_PATH = "HKCU\\Environment";
124
134
  const MACHINE_ENV_KEY_PATH = "HKLM\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment";
125
135
  const USER_ENV_REGISTRY_PATH = "HKCU:\\Environment";
@@ -149,6 +159,113 @@ function normalizeDsc(arg) {
149
159
  resource.dependsOn = deps;
150
160
  return withDscToken(resource);
151
161
  }
162
+ const BOOLEAN_WINDOWS_SETTINGS = new Set([
163
+ "DeveloperMode",
164
+ "SetTimeZoneAutomatically",
165
+ "EnableTransparency",
166
+ "ShowAccentColorOnStartAndTaskbar",
167
+ "ShowAccentColorOnTitleBarsAndWindowBorders",
168
+ "AutoColorization",
169
+ "ShowRecentList",
170
+ "ShowRecommendedList",
171
+ "TaskbarBadges",
172
+ "DesktopTaskbarBadges",
173
+ "TaskbarMultiMon",
174
+ "DesktopTaskbarMultiMon",
175
+ "NotifyOnUsbErrors",
176
+ "NotifyOnWeakCharger",
177
+ ]);
178
+ const COLOR_MODE_VALUES = ["Light", "Dark"];
179
+ const TASKBAR_ALIGNMENT_VALUES = ["Left", "Center"];
180
+ const TASKBAR_GROUPING_VALUES = ["Always", "WhenFull", "Never"];
181
+ const TASKBAR_MULTI_MON_MODE_VALUES = ["Duplicate", "PrimaryAndWindow", "WindowOnly"];
182
+ const START_FOLDER_VALUES = [
183
+ "Documents",
184
+ "Downloads",
185
+ "Music",
186
+ "Pictures",
187
+ "Videos",
188
+ "Network",
189
+ "UserProfile",
190
+ "Explorer",
191
+ "Settings",
192
+ ];
193
+ const WINDOWS_SETTING_VALIDATORS = {
194
+ TaskbarAlignment: enumSettingValidator(TASKBAR_ALIGNMENT_VALUES),
195
+ AppColorMode: enumSettingValidator(COLOR_MODE_VALUES),
196
+ SystemColorMode: enumSettingValidator(COLOR_MODE_VALUES),
197
+ TimeZone: stringSettingValidator,
198
+ StartFolders: startFoldersSettingValidator,
199
+ TaskbarGroupingMode: enumSettingValidator(TASKBAR_GROUPING_VALUES),
200
+ TaskbarMultiMonMode: enumSettingValidator(TASKBAR_MULTI_MON_MODE_VALUES),
201
+ DesktopTaskbarMultiMonMode: enumSettingValidator(TASKBAR_MULTI_MON_MODE_VALUES),
202
+ };
203
+ for (const key of BOOLEAN_WINDOWS_SETTINGS) {
204
+ WINDOWS_SETTING_VALIDATORS[key] = booleanSettingValidator;
205
+ }
206
+ function supportedWindowsSettings() {
207
+ return Object.keys(WINDOWS_SETTING_VALIDATORS).sort();
208
+ }
209
+ function booleanSettingValidator(value, key) {
210
+ if (typeof value !== "boolean") {
211
+ throw new Error(`windows.setting({ ${key} }) must be a boolean`);
212
+ }
213
+ return value;
214
+ }
215
+ function stringSettingValidator(value, key) {
216
+ if (typeof value !== "string" || value.length === 0) {
217
+ throw new Error(`windows.setting({ ${key} }) must be a non-empty string`);
218
+ }
219
+ return value;
220
+ }
221
+ function enumSettingValidator(allowed) {
222
+ return (value, key) => {
223
+ if (typeof value !== "string" || !allowed.includes(value)) {
224
+ throw new Error(`windows.setting({ ${key} }) must be one of: ${allowed.join(", ")}`);
225
+ }
226
+ return value;
227
+ };
228
+ }
229
+ function startFoldersSettingValidator(value, key) {
230
+ if (!Array.isArray(value) || value.some((entry) => typeof entry !== "string")) {
231
+ throw new Error(`windows.setting({ ${key} }) must be an array of: ${START_FOLDER_VALUES.join(", ")}`);
232
+ }
233
+ const invalid = value.find((entry) => !START_FOLDER_VALUES.includes(entry));
234
+ if (invalid) {
235
+ throw new Error(`windows.setting({ ${key} }) contains unsupported folder "${invalid}". ` +
236
+ `Supported folders: ${START_FOLDER_VALUES.join(", ")}.`);
237
+ }
238
+ return value;
239
+ }
240
+ function normalizeSetting(settings, opts) {
241
+ if (!settings || typeof settings !== "object" || Array.isArray(settings)) {
242
+ throw new Error("windows.setting(settings) requires a settings object");
243
+ }
244
+ if (opts !== undefined && (opts === null || typeof opts !== "object" || Array.isArray(opts))) {
245
+ throw new Error("windows.setting options must be an object when provided");
246
+ }
247
+ const properties = {};
248
+ for (const [key, value] of Object.entries(settings)) {
249
+ const validator = WINDOWS_SETTING_VALIDATORS[key];
250
+ if (!validator) {
251
+ throw new Error(`windows.setting(...) does not support setting "${key}". ` +
252
+ `Supported settings: ${supportedWindowsSettings().join(", ")}.`);
253
+ }
254
+ properties[key] = validator(value, key);
255
+ }
256
+ if (Object.keys(properties).length === 0) {
257
+ throw new Error("windows.setting(settings) requires at least one supported setting");
258
+ }
259
+ const resource = {
260
+ resourceType: WINDOWS_SETTINGS_RESOURCE,
261
+ name: "Windows Settings",
262
+ properties,
263
+ };
264
+ const deps = resolveDependsOn(opts?.dependsOn);
265
+ if (deps)
266
+ resource.dependsOn = deps;
267
+ return withDscMetadata(withDscToken(resource), { kind: "setting" });
268
+ }
152
269
  function normalizeEnvOpts(opts, helper) {
153
270
  if (opts === undefined)
154
271
  return undefined;
@@ -190,7 +307,13 @@ function registryDsc(opts) {
190
307
  };
191
308
  if (opts.dependsOn)
192
309
  resource.dependsOn = opts.dependsOn;
193
- return withDscToken(resource);
310
+ return withDscMetadata(withDscToken(resource), {
311
+ kind: "env",
312
+ action: opts.exists ? "set" : "remove",
313
+ name: opts.valueName,
314
+ value: opts.value,
315
+ scope: opts.scope,
316
+ });
194
317
  }
195
318
  function normalizeEnv(name, ensure, value, opts) {
196
319
  const normalizedOpts = normalizeEnvOpts(opts, "windows.env.*");
@@ -207,6 +330,7 @@ function normalizeEnv(name, ensure, value, opts) {
207
330
  valueName: name,
208
331
  value,
209
332
  exists: ensure === "Present",
333
+ scope,
210
334
  dependsOn: resolveDependsOn(normalizedOpts?.dependsOn),
211
335
  });
212
336
  }
@@ -228,8 +352,100 @@ function normalizePath(value, ensure, opts) {
228
352
  const deps = resolveDependsOn(normalizedOpts?.dependsOn);
229
353
  if (deps)
230
354
  resource.dependsOn = deps;
355
+ return withDscMetadata(withDscToken(resource), {
356
+ kind: "path",
357
+ action: ensure === "Present" ? "add" : "remove",
358
+ value,
359
+ scope,
360
+ });
361
+ }
362
+ function normalizeFileOpts(opts, helper) {
363
+ if (opts === undefined)
364
+ return {};
365
+ if (opts === null || typeof opts !== "object" || Array.isArray(opts)) {
366
+ throw new Error(`${helper} options must be an object when provided`);
367
+ }
368
+ for (const key of ["force", "backup", "recursive", "elevate"]) {
369
+ if (opts[key] !== undefined && typeof opts[key] !== "boolean") {
370
+ throw new Error(`${helper} option "${key}" must be a boolean`);
371
+ }
372
+ }
373
+ if (opts.encoding !== undefined &&
374
+ opts.encoding !== "utf8" &&
375
+ opts.encoding !== "utf8bom" &&
376
+ opts.encoding !== "ascii") {
377
+ throw new Error(`${helper} encoding "${opts.encoding}" is invalid; expected "utf8", "utf8bom", or "ascii"`);
378
+ }
379
+ return opts;
380
+ }
381
+ function fileDsc(name, properties, opts) {
382
+ const resource = {
383
+ resourceType: WINDOWS_POWERSHELL_SCRIPT_RESOURCE,
384
+ name,
385
+ properties,
386
+ };
387
+ const deps = resolveDependsOn(opts.dependsOn);
388
+ if (deps)
389
+ resource.dependsOn = deps;
390
+ if (opts.elevate)
391
+ resource.elevated = true;
231
392
  return withDscToken(resource);
232
393
  }
394
+ function normalizeFileText(target, content, opts) {
395
+ const normalizedOpts = normalizeFileOpts(opts, "windows.file.text");
396
+ if (!target || typeof target !== "string") {
397
+ throw new Error("windows.file.text(target) requires a non-empty target path");
398
+ }
399
+ if (typeof content !== "string") {
400
+ throw new Error("windows.file.text(target, content) requires string content");
401
+ }
402
+ const encoding = normalizedOpts.encoding ?? "utf8";
403
+ return fileDsc(`Write file ${target}`, buildFileTextScriptProperties({
404
+ target,
405
+ content,
406
+ encoding,
407
+ force: normalizedOpts.force ?? false,
408
+ backup: normalizedOpts.backup ?? false,
409
+ }), normalizedOpts);
410
+ }
411
+ function normalizeFileSymlink(target, source, opts) {
412
+ const normalizedOpts = normalizeFileOpts(opts, "windows.file.symlink");
413
+ if (!target || typeof target !== "string") {
414
+ throw new Error("windows.file.symlink(target) requires a non-empty target path");
415
+ }
416
+ if (!source || typeof source !== "string") {
417
+ throw new Error("windows.file.symlink(target, source) requires a non-empty source path");
418
+ }
419
+ return fileDsc(`Link file ${target}`, buildFileSymlinkScriptProperties({
420
+ target,
421
+ source,
422
+ recursive: normalizedOpts.recursive ?? false,
423
+ force: normalizedOpts.force ?? false,
424
+ backup: normalizedOpts.backup ?? false,
425
+ }), normalizedOpts);
426
+ }
427
+ function normalizeFileCopy(target, source, opts) {
428
+ const normalizedOpts = normalizeFileOpts(opts, "windows.file.copy");
429
+ if (!target || typeof target !== "string") {
430
+ throw new Error("windows.file.copy(target) requires a non-empty target path");
431
+ }
432
+ if (!source || typeof source !== "string") {
433
+ throw new Error("windows.file.copy(target, source) requires a non-empty source path");
434
+ }
435
+ return fileDsc(`Copy file ${target}`, buildFileCopyScriptProperties({
436
+ target,
437
+ source,
438
+ force: normalizedOpts.force ?? false,
439
+ backup: normalizedOpts.backup ?? false,
440
+ }), normalizedOpts);
441
+ }
442
+ function normalizeFileRemove(target, opts) {
443
+ const normalizedOpts = normalizeFileOpts(opts, "windows.file.remove");
444
+ if (!target || typeof target !== "string") {
445
+ throw new Error("windows.file.remove(target) requires a non-empty target path");
446
+ }
447
+ return fileDsc(`Remove file ${target}`, buildFileRemoveScriptProperties({ target }), normalizedOpts);
448
+ }
233
449
  function buildPathScriptProperties(opts) {
234
450
  const registryPath = envRegistryPath(opts.scope);
235
451
  const target = envTarget(opts.scope);
@@ -281,6 +497,277 @@ function buildPathScriptProperties(opts) {
281
497
  ].join("\n"),
282
498
  };
283
499
  }
500
+ function buildFileTextScriptProperties(opts) {
501
+ const vars = [
502
+ `$target = Expand-WinixPath ${psSingleQuoted(opts.target)}`,
503
+ `$content = ${psSingleQuoted(opts.content)}`,
504
+ `$encoding = ${psSingleQuoted(opts.encoding)}`,
505
+ `$force = ${psBoolean(opts.force)}`,
506
+ `$backup = ${psBoolean(opts.backup)}`,
507
+ ];
508
+ return {
509
+ getScript: [
510
+ ...filePathPrelude(),
511
+ `$target = Expand-WinixPath ${psSingleQuoted(opts.target)}`,
512
+ "if (Test-Path -LiteralPath $target -PathType Leaf) { [IO.File]::ReadAllText($target) } else { '' }",
513
+ ].join("\n"),
514
+ testScript: [
515
+ ...fileTextPrelude(),
516
+ ...vars,
517
+ "$desired = Get-WinixTextBytes $content $encoding",
518
+ "if (-not (Test-Path -LiteralPath $target -PathType Leaf)) { return $false }",
519
+ "$actual = [IO.File]::ReadAllBytes($target)",
520
+ "Test-WinixBytesEqual $actual $desired",
521
+ ].join("\n"),
522
+ setScript: [
523
+ ...fileTextPrelude(),
524
+ ...vars,
525
+ "$desired = Get-WinixTextBytes $content $encoding",
526
+ "if (Test-Path -LiteralPath $target -PathType Leaf) {",
527
+ " $actual = [IO.File]::ReadAllBytes($target)",
528
+ " if (Test-WinixBytesEqual $actual $desired) { return }",
529
+ "}",
530
+ "Move-WinixExistingTarget $target $force $backup",
531
+ "Ensure-WinixParentDirectory $target",
532
+ "[IO.File]::WriteAllBytes($target, $desired)",
533
+ ].join("\n"),
534
+ };
535
+ }
536
+ function buildFileSymlinkScriptProperties(opts) {
537
+ const vars = fileScriptVars({
538
+ target: opts.target,
539
+ source: opts.source,
540
+ recursive: opts.recursive,
541
+ force: opts.force,
542
+ backup: opts.backup,
543
+ });
544
+ return {
545
+ getScript: [
546
+ ...fileSymlinkPrelude(),
547
+ `$target = Expand-WinixPath ${psSingleQuoted(opts.target)}`,
548
+ "if (Test-Path -LiteralPath $target) { (Get-Item -LiteralPath $target -Force).LinkType } else { '' }",
549
+ ].join("\n"),
550
+ testScript: [
551
+ ...fileSymlinkPrelude(),
552
+ ...vars,
553
+ "if ($recursive) { Test-WinixRecursiveSymlink $source $target } else { Test-WinixSymlink $source $target }",
554
+ ].join("\n"),
555
+ setScript: [
556
+ ...fileSymlinkPrelude(),
557
+ ...vars,
558
+ "Assert-WinixCanCreateSymlink",
559
+ "if (-not (Test-Path -LiteralPath $source)) { throw \"Source path does not exist: $source\" }",
560
+ "if ($recursive) {",
561
+ " Set-WinixRecursiveSymlink $source $target $force $backup",
562
+ "} else {",
563
+ " Set-WinixSymlink $source $target $force $backup",
564
+ "}",
565
+ ].join("\n"),
566
+ };
567
+ }
568
+ function buildFileCopyScriptProperties(opts) {
569
+ const vars = fileScriptVars({
570
+ target: opts.target,
571
+ source: opts.source,
572
+ force: opts.force,
573
+ backup: opts.backup,
574
+ });
575
+ return {
576
+ getScript: [
577
+ ...filePathPrelude(),
578
+ `$target = Expand-WinixPath ${psSingleQuoted(opts.target)}`,
579
+ "if (Test-Path -LiteralPath $target) { $target } else { '' }",
580
+ ].join("\n"),
581
+ testScript: [
582
+ ...fileCopyPrelude(),
583
+ ...vars,
584
+ "Test-WinixCopy $source $target",
585
+ ].join("\n"),
586
+ setScript: [
587
+ ...fileCopyPrelude(),
588
+ ...vars,
589
+ "if (-not (Test-Path -LiteralPath $source)) { throw \"Source path does not exist: $source\" }",
590
+ "if (Test-WinixCopy $source $target) { return }",
591
+ "Move-WinixExistingTarget $target $force $backup",
592
+ "Ensure-WinixParentDirectory $target",
593
+ "if (Test-Path -LiteralPath $source -PathType Container) {",
594
+ " New-Item -ItemType Directory -Force -Path $target | Out-Null",
595
+ " Copy-Item -Path (Join-Path $source '*') -Destination $target -Recurse -Force",
596
+ "} else {",
597
+ " Copy-Item -LiteralPath $source -Destination $target -Force",
598
+ "}",
599
+ ].join("\n"),
600
+ };
601
+ }
602
+ function buildFileRemoveScriptProperties(opts) {
603
+ return {
604
+ getScript: [
605
+ ...filePathPrelude(),
606
+ `$target = Expand-WinixPath ${psSingleQuoted(opts.target)}`,
607
+ "if (Test-Path -LiteralPath $target) { $target } else { '' }",
608
+ ].join("\n"),
609
+ testScript: [
610
+ ...filePathPrelude(),
611
+ `$target = Expand-WinixPath ${psSingleQuoted(opts.target)}`,
612
+ "-not (Test-Path -LiteralPath $target)",
613
+ ].join("\n"),
614
+ setScript: [
615
+ ...filePathPrelude(),
616
+ `$target = Expand-WinixPath ${psSingleQuoted(opts.target)}`,
617
+ "if (-not (Test-Path -LiteralPath $target)) { return }",
618
+ "$item = Get-Item -LiteralPath $target -Force",
619
+ "if ($item.PSIsContainer -and $null -eq $item.LinkType) {",
620
+ " throw \"Refusing to remove real directory: $target\"",
621
+ "}",
622
+ "Remove-Item -LiteralPath $target -Force",
623
+ ].join("\n"),
624
+ };
625
+ }
626
+ function fileScriptVars(values) {
627
+ return Object.entries(values).map(([name, value]) => typeof value === "boolean"
628
+ ? `$${name} = ${psBoolean(value)}`
629
+ : `$${name} = Expand-WinixPath ${psSingleQuoted(value)}`);
630
+ }
631
+ function filePathPrelude() {
632
+ return [
633
+ "function Expand-WinixPath([string]$Path) { [Environment]::ExpandEnvironmentVariables($Path) }",
634
+ ];
635
+ }
636
+ function fileTextPrelude() {
637
+ return [
638
+ ...filePathPrelude(),
639
+ "function Ensure-WinixParentDirectory([string]$Path) {",
640
+ " $parent = Split-Path -Parent $Path",
641
+ " if (-not [string]::IsNullOrEmpty($parent)) { New-Item -ItemType Directory -Force -Path $parent | Out-Null }",
642
+ "}",
643
+ "function Test-WinixBytesEqual([byte[]]$Actual, [byte[]]$Desired) {",
644
+ " if ($Actual.Length -ne $Desired.Length) { return $false }",
645
+ " for ($i = 0; $i -lt $Actual.Length; $i++) { if ($Actual[$i] -ne $Desired[$i]) { return $false } }",
646
+ " return $true",
647
+ "}",
648
+ "function Get-WinixTextBytes([string]$Content, [string]$EncodingName) {",
649
+ " if ($EncodingName -eq 'ascii') { return [byte[]][Text.Encoding]::ASCII.GetBytes($Content) }",
650
+ " $encoder = [Text.UTF8Encoding]::new($EncodingName -eq 'utf8bom')",
651
+ " return [byte[]]($encoder.GetPreamble() + $encoder.GetBytes($Content))",
652
+ "}",
653
+ ...fileMoveTargetPrelude(),
654
+ ];
655
+ }
656
+ function fileMoveTargetPrelude() {
657
+ return [
658
+ "function Move-WinixExistingTarget([string]$Path, [bool]$Force, [bool]$Backup) {",
659
+ " if (-not (Test-Path -LiteralPath $Path)) { return }",
660
+ " if ($Backup) {",
661
+ " $backupPath = \"$Path.bak\"",
662
+ " if (Test-Path -LiteralPath $backupPath) { throw \"Backup target already exists: $backupPath\" }",
663
+ " Move-Item -LiteralPath $Path -Destination $backupPath",
664
+ " return",
665
+ " }",
666
+ " if (-not $Force) { throw \"Target already exists and differs: $Path. Pass force: true or backup: true.\" }",
667
+ " $item = Get-Item -LiteralPath $Path -Force",
668
+ " if ($item.PSIsContainer -and $null -eq $item.LinkType) {",
669
+ " $children = @(Get-ChildItem -LiteralPath $Path -Force -ErrorAction SilentlyContinue)",
670
+ " if ($children.Count -gt 0) { throw \"Refusing to delete populated directory: $Path. Move it manually or use backup: true.\" }",
671
+ " }",
672
+ " Remove-Item -LiteralPath $Path -Force -Recurse",
673
+ "}",
674
+ ];
675
+ }
676
+ function fileSymlinkPrelude() {
677
+ return [
678
+ ...filePathPrelude(),
679
+ "function Ensure-WinixParentDirectory([string]$Path) {",
680
+ " $parent = Split-Path -Parent $Path",
681
+ " if (-not [string]::IsNullOrEmpty($parent)) { New-Item -ItemType Directory -Force -Path $parent | Out-Null }",
682
+ "}",
683
+ ...fileMoveTargetPrelude(),
684
+ "function Test-WinixSymlink([string]$Source, [string]$Target) {",
685
+ " if (-not (Test-Path -LiteralPath $Target)) { return $false }",
686
+ " $item = Get-Item -LiteralPath $Target -Force",
687
+ " ($item.LinkType -eq 'SymbolicLink') -and [string]::Equals([string]$item.Target, $Source, [StringComparison]::OrdinalIgnoreCase)",
688
+ "}",
689
+ "function Invoke-WinixMklink([string]$Source, [string]$Target) {",
690
+ " Ensure-WinixParentDirectory $Target",
691
+ " $isDirectory = Test-Path -LiteralPath $Source -PathType Container",
692
+ " $flag = if ($isDirectory) { '/D ' } else { '' }",
693
+ " & $env:ComSpec /c \"mklink $flag`\"$Target`\" `\"$Source`\"\"",
694
+ " if ($LASTEXITCODE -ne 0) { throw \"mklink failed with exit code $LASTEXITCODE\" }",
695
+ "}",
696
+ "function Set-WinixSymlink([string]$Source, [string]$Target, [bool]$Force, [bool]$Backup) {",
697
+ " if (Test-WinixSymlink $Source $Target) { return }",
698
+ " Move-WinixExistingTarget $Target $Force $Backup",
699
+ " Invoke-WinixMklink $Source $Target",
700
+ "}",
701
+ "function Get-WinixRelativePath([string]$Root, [string]$Path) {",
702
+ " $prefix = $Root.TrimEnd('\\') + '\\'",
703
+ " $Path.Substring($prefix.Length)",
704
+ "}",
705
+ "function Test-WinixRecursiveSymlink([string]$Source, [string]$Target) {",
706
+ " if (-not (Test-Path -LiteralPath $Source -PathType Container)) { return $false }",
707
+ " if (-not (Test-Path -LiteralPath $Target -PathType Container)) { return $false }",
708
+ " $root = (Resolve-Path -LiteralPath $Source).ProviderPath",
709
+ " foreach ($dir in Get-ChildItem -LiteralPath $root -Recurse -Force -Directory) {",
710
+ " $relative = Get-WinixRelativePath $root $dir.FullName",
711
+ " if (-not (Test-Path -LiteralPath (Join-Path $Target $relative) -PathType Container)) { return $false }",
712
+ " }",
713
+ " foreach ($file in Get-ChildItem -LiteralPath $root -Recurse -Force -File) {",
714
+ " $relative = Get-WinixRelativePath $root $file.FullName",
715
+ " if (-not (Test-WinixSymlink $file.FullName (Join-Path $Target $relative))) { return $false }",
716
+ " }",
717
+ " return $true",
718
+ "}",
719
+ "function Set-WinixRecursiveSymlink([string]$Source, [string]$Target, [bool]$Force, [bool]$Backup) {",
720
+ " if (-not (Test-Path -LiteralPath $Source -PathType Container)) { throw \"Recursive symlink source must be a directory: $Source\" }",
721
+ " if (Test-WinixRecursiveSymlink $Source $Target) { return }",
722
+ " Move-WinixExistingTarget $Target $Force $Backup",
723
+ " New-Item -ItemType Directory -Force -Path $Target | Out-Null",
724
+ " $root = (Resolve-Path -LiteralPath $Source).ProviderPath",
725
+ " foreach ($dir in Get-ChildItem -LiteralPath $root -Recurse -Force -Directory) {",
726
+ " New-Item -ItemType Directory -Force -Path (Join-Path $Target (Get-WinixRelativePath $root $dir.FullName)) | Out-Null",
727
+ " }",
728
+ " foreach ($file in Get-ChildItem -LiteralPath $root -Recurse -Force -File) {",
729
+ " Set-WinixSymlink $file.FullName (Join-Path $Target (Get-WinixRelativePath $root $file.FullName)) $Force $Backup",
730
+ " }",
731
+ "}",
732
+ "function Assert-WinixCanCreateSymlink {",
733
+ " $principal = [Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()",
734
+ " if ($principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { return }",
735
+ " $devMode = Get-ItemPropertyValue -Path 'HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\AppModelUnlock' -Name AllowDevelopmentWithoutDevLicense -ErrorAction SilentlyContinue",
736
+ " if ($devMode -eq 1) { return }",
737
+ " throw 'Creating Windows symlinks requires elevation or Developer Mode. Enable Developer Mode in Windows Settings, or pass elevate: true.'",
738
+ "}",
739
+ ];
740
+ }
741
+ function fileCopyPrelude() {
742
+ return [
743
+ ...fileTextPrelude(),
744
+ "function Get-WinixRelativePath([string]$Root, [string]$Path) {",
745
+ " $prefix = $Root.TrimEnd('\\') + '\\'",
746
+ " $Path.Substring($prefix.Length)",
747
+ "}",
748
+ "function Test-WinixCopy([string]$Source, [string]$Target) {",
749
+ " if (-not (Test-Path -LiteralPath $Source) -or -not (Test-Path -LiteralPath $Target)) { return $false }",
750
+ " if (Test-Path -LiteralPath $Source -PathType Leaf) {",
751
+ " if (-not (Test-Path -LiteralPath $Target -PathType Leaf)) { return $false }",
752
+ " return Test-WinixBytesEqual ([IO.File]::ReadAllBytes($Target)) ([IO.File]::ReadAllBytes($Source))",
753
+ " }",
754
+ " if (-not (Test-Path -LiteralPath $Target -PathType Container)) { return $false }",
755
+ " $root = (Resolve-Path -LiteralPath $Source).ProviderPath",
756
+ " foreach ($dir in Get-ChildItem -LiteralPath $root -Recurse -Force -Directory) {",
757
+ " if (-not (Test-Path -LiteralPath (Join-Path $Target (Get-WinixRelativePath $root $dir.FullName)) -PathType Container)) { return $false }",
758
+ " }",
759
+ " foreach ($file in Get-ChildItem -LiteralPath $root -Recurse -Force -File) {",
760
+ " $targetFile = Join-Path $Target (Get-WinixRelativePath $root $file.FullName)",
761
+ " if (-not (Test-Path -LiteralPath $targetFile -PathType Leaf)) { return $false }",
762
+ " if (-not (Test-WinixBytesEqual ([IO.File]::ReadAllBytes($targetFile)) ([IO.File]::ReadAllBytes($file.FullName)))) { return $false }",
763
+ " }",
764
+ " return $true",
765
+ "}",
766
+ ];
767
+ }
768
+ function psBoolean(value) {
769
+ return value ? "$true" : "$false";
770
+ }
284
771
  function psSingleQuoted(value) {
285
772
  return `'${value.replace(/'/g, "''")}'`;
286
773
  }
@@ -317,6 +804,7 @@ export const windows = {
317
804
  const fragment = { windows: { dsc: [resource] } };
318
805
  return asHandle(fragment, { kind: "dsc", token: resource.token });
319
806
  },
807
+ setting: (settings, opts) => dscHandle(normalizeSetting(settings, opts)),
320
808
  env: {
321
809
  set: (name, value, opts) => dscHandle(normalizeEnv(name, "Present", value, opts)),
322
810
  remove: (name, opts) => dscHandle(normalizeEnv(name, "Absent", undefined, opts)),
@@ -325,4 +813,10 @@ export const windows = {
325
813
  add: (value, opts) => dscHandle(normalizePath(value, "Present", opts)),
326
814
  remove: (value, opts) => dscHandle(normalizePath(value, "Absent", opts)),
327
815
  },
816
+ file: {
817
+ text: (target, content, opts) => dscHandle(normalizeFileText(target, content, opts)),
818
+ symlink: (target, source, opts) => dscHandle(normalizeFileSymlink(target, source, opts)),
819
+ copy: (target, source, opts) => dscHandle(normalizeFileCopy(target, source, opts)),
820
+ remove: (target, opts) => dscHandle(normalizeFileRemove(target, opts)),
821
+ },
328
822
  };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
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, } from "./types/index.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";
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,4 @@ 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 { AccountGroupFactory, AccountGroupMember, AccountGroupOpts, AccountNamespace, AccountOpts, AccountUserFactory, AccountUserRef, ActivationOpts, BinaryReleaseArch, BinaryReleaseCompletions, 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, WinPackageArg, WinPackageSpec, WinPathNamespace, WinRawCommandArg, WinRawCommandSpec } from "./helpers/index.js";
12
+ export type { AccountGroupFactory, AccountGroupMember, AccountGroupOpts, AccountNamespace, AccountOpts, AccountUserFactory, AccountUserRef, ActivationOpts, BinaryReleaseArch, BinaryReleaseCompletions, 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";
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Escape content for a Nix double-quoted string without changing its value.
3
+ */
4
+ export declare function escapeNixDoubleQuoted(value: string): string;
5
+ /**
6
+ * Serialize a JavaScript string as a behavior-preserving Nix literal.
7
+ */
8
+ export declare function nixStringLiteral(value: string): string;
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Escape content for a Nix double-quoted string without changing its value.
3
+ */
4
+ export function escapeNixDoubleQuoted(value) {
5
+ if (value.includes("\0")) {
6
+ throw new Error("Nix strings cannot contain null bytes");
7
+ }
8
+ return value
9
+ .replace(/\\/g, "\\\\")
10
+ .replace(/"/g, '\\"')
11
+ .replace(/\$\{/g, "\\${")
12
+ .replace(/\n/g, "\\n")
13
+ .replace(/\r/g, "\\r")
14
+ .replace(/\t/g, "\\t");
15
+ }
16
+ /**
17
+ * Serialize a JavaScript string as a behavior-preserving Nix literal.
18
+ */
19
+ export function nixStringLiteral(value) {
20
+ return `"${escapeNixDoubleQuoted(value)}"`;
21
+ }
@@ -8,8 +8,8 @@ export interface HomeConfig extends Record<string, unknown> {
8
8
  stateVersion?: string;
9
9
  packages?: PackageRef[];
10
10
  file?: Record<string, HomeFile> | NixExpr;
11
- sessionVariables?: Record<string, string>;
12
- sessionPath?: string[];
11
+ sessionVariables?: Record<string, string | NixExpr>;
12
+ sessionPath?: (string | NixExpr)[];
13
13
  activation?: Record<string, HomeActivation | Script>;
14
14
  }
15
15
  export interface HomeFile extends Record<string, unknown> {
@@ -34,8 +34,8 @@ export interface HomeOptions extends Record<string, unknown> {
34
34
  services?: Attrs;
35
35
  xdg?: XdgOptions;
36
36
  packages?: PackageRef[];
37
- sessionVariables?: Record<string, string>;
38
- sessionPath?: string[];
37
+ sessionVariables?: Record<string, string | NixExpr>;
38
+ sessionPath?: (string | NixExpr)[];
39
39
  activation?: Record<string, HomeActivation | Script>;
40
40
  manual?: {
41
41
  manpages?: {