@adrifer/winix 0.2.0-preview.4 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -281,6 +281,8 @@ Use `nix.*` when a value needs to be a Nix expression:
281
281
  ```ts
282
282
  nix.pkg("zsh")
283
283
  nix.bin("git", "git")
284
+ nix.homePath(".config/nvim/init.lua")
285
+ nix.pkgPath("git", "share/git-core/templates")
284
286
  nix.str`${nix.pkg("neovim")}/bin/nvim`
285
287
  nix.script`
286
288
  echo "hello from activation"
@@ -288,6 +290,13 @@ nix.script`
288
290
  nix.lib.mkForce(["https://cache.nixos.org/"])
289
291
  ```
290
292
 
293
+ `nix.homePath(relativePath)` builds a path below
294
+ `config.home.homeDirectory`, while `nix.pkgPath(packageName, relativePath)`
295
+ builds one below `pkgs.<packageName>`. Both return a typed `NixExpr`, safely
296
+ quote string content, ignore leading `/` characters in the relative path,
297
+ preserve all other characters, and omit the trailing slash for an empty path.
298
+ Use POSIX `/` separators; backslashes are preserved as literal characters.
299
+
291
300
  For prebuilt single-binary CLI releases (the `azd`, `gh`, `kubectl`,
292
301
  `1password` family), use `nix.binaryRelease()` instead of hand-rolling
293
302
  the `stdenvNoCC.mkDerivation` boilerplate:
@@ -1,5 +1,6 @@
1
1
  // Nix backend: generates .nix files from evaluated host IR
2
2
  import { posix as pathPosix } from "node:path";
3
+ import { nixStringLiteral } from "../../nix/serialize.js";
3
4
  /**
4
5
  * Generate Nix files from an evaluated workspace.
5
6
  */
@@ -23,7 +24,7 @@ function generateFlake(workspace, hosts) {
23
24
  const nixosHosts = hosts
24
25
  .filter((h) => Object.keys(h.nixos).length > 0)
25
26
  .map((h) => ` nixosConfigurations.${h.name} = nixpkgs.lib.nixosSystem {\n` +
26
- ` system = "${systemForHost(h, "nixos")}";\n` +
27
+ ` system = ${nixStringLiteral(systemForHost(h, "nixos"))};\n` +
27
28
  ` modules = [ ${nixRelativePath("hosts", `${h.name}.nix`)} ];\n` +
28
29
  ` specialArgs = { inherit inputs; };\n` +
29
30
  ` };`)
@@ -31,7 +32,7 @@ function generateFlake(workspace, hosts) {
31
32
  const darwinHosts = hosts
32
33
  .filter((h) => Object.keys(h.darwin).length > 0)
33
34
  .map((h) => ` darwinConfigurations.${h.name} = inputs.nix-darwin.lib.darwinSystem {\n` +
34
- ` system = "${systemForHost(h, "darwin")}";\n` +
35
+ ` system = ${nixStringLiteral(systemForHost(h, "darwin"))};\n` +
35
36
  ` modules = [ ${nixRelativePath("hosts", `${h.name}.nix`)} ];\n` +
36
37
  ` specialArgs = { inherit inputs; };\n` +
37
38
  ` };`)
@@ -55,12 +56,12 @@ function formatInput(name, def) {
55
56
  const nixName = inputNixName(name, def);
56
57
  if (typeof def === "string") {
57
58
  const url = def.startsWith("github:") ? def : `github:NixOS/nixpkgs/${def}`;
58
- return ` ${nixName}.url = "${url}";`;
59
+ return ` ${nixName}.url = ${nixStringLiteral(url)};`;
59
60
  }
60
- const lines = [` ${nixName}.url = "${def.url}";`];
61
+ const lines = [` ${nixName}.url = ${nixStringLiteral(def.url)};`];
61
62
  if (def.follows) {
62
63
  for (const [key, value] of Object.entries(def.follows)) {
63
- lines.push(` ${nixName}.inputs.${key}.follows = "${value}";`);
64
+ lines.push(` ${nixName}.inputs.${key}.follows = ${nixStringLiteral(value)};`);
64
65
  }
65
66
  }
66
67
  return lines.join("\n");
@@ -285,7 +286,7 @@ function formatNixValue(value) {
285
286
  if (typeof value === "string") {
286
287
  if (isPkgsReference(value))
287
288
  return value;
288
- return `"${value}"`;
289
+ return nixStringLiteral(value);
289
290
  }
290
291
  if (typeof value === "number")
291
292
  return String(value);
@@ -297,7 +298,7 @@ function formatNixValue(value) {
297
298
  if (isPlainObject(value)) {
298
299
  return formatInlineAttrSet(value);
299
300
  }
300
- return `"${String(value)}"`;
301
+ return nixStringLiteral(String(value));
301
302
  }
302
303
  function formatInlineAttrSet(obj) {
303
304
  // Scope-specific package rewriting only applies to top-level fragment fields;
@@ -319,7 +320,7 @@ function formatAttrPath(path) {
319
320
  return path.map(formatAttrKey).join(".");
320
321
  }
321
322
  function formatAttrKey(key) {
322
- return needsQuoting(key) ? JSON.stringify(key) : key;
323
+ return needsQuoting(key) ? nixStringLiteral(key) : key;
323
324
  }
324
325
  function needsQuoting(key) {
325
326
  if (NIX_KEYWORDS.has(key))
@@ -32,6 +32,7 @@ export { isWindowsHost } from "./host.js";
32
32
  const DSC_SCHEMA = "https://raw.githubusercontent.com/PowerShell/DSC/main/schemas/2023/08/config/document.json";
33
33
  const WINGET_PACKAGE_TYPE = "Microsoft.WinGet/Package";
34
34
  const RUN_COMMAND_ON_SET_TYPE = "Microsoft.DSC.Transitional/RunCommandOnSet";
35
+ const WINDOWS_SETTINGS_MODULE_COMMAND_NAME = "Ensure Microsoft Windows Settings module";
35
36
  /**
36
37
  * Generate Windows bundles for every Windows host in the evaluated workspace.
37
38
  * Non-Windows hosts are skipped.
@@ -55,8 +56,9 @@ export function generateWindows(evaluatedHosts, lock = emptyWindowsLock()) {
55
56
  */
56
57
  function generateConfiguration(hostName, win, lock) {
57
58
  const packages = sortedPackages(win.packages ?? {});
58
- const commands = win.commands ?? [];
59
- const dscResources = win.dsc ?? [];
59
+ const prepared = prepareWindowsDscResources(win.commands ?? [], win.dsc ?? []);
60
+ const commands = prepared.commands;
61
+ const dscResources = prepared.dscResources;
60
62
  const lines = [];
61
63
  lines.push(`# yaml-language-server: $schema=${DSC_SCHEMA}`);
62
64
  lines.push(`# Generated by Winix for host "${hostName}". Do not edit.`);
@@ -87,6 +89,191 @@ function generateConfiguration(hostName, win, lock) {
87
89
  }
88
90
  return lines.join("\n") + "\n";
89
91
  }
92
+ function prepareWindowsDscResources(commands, resources) {
93
+ const envResolvedResources = resolveManagedEnvironmentReferences(resources);
94
+ if (!envResolvedResources.some((resource) => resource.winix?.kind === "setting")) {
95
+ return { commands: [...commands], dscResources: envResolvedResources };
96
+ }
97
+ const ensureModule = createWindowsSettingsEnsureCommand();
98
+ const ensureRef = { kind: "dsc", token: ensureModule.token };
99
+ return {
100
+ commands: [...commands],
101
+ dscResources: [
102
+ ensureModule,
103
+ ...envResolvedResources.map((resource) => {
104
+ if (resource.winix?.kind !== "setting")
105
+ return resource;
106
+ return cloneDscResource(resource, resource.properties, [
107
+ ensureRef,
108
+ ...(resource.dependsOn ?? []),
109
+ ]);
110
+ }),
111
+ ],
112
+ };
113
+ }
114
+ function createWindowsSettingsEnsureCommand() {
115
+ // Microsoft.Windows.Settings currently publishes the WindowsSettings resource
116
+ // as a prerelease module (the upstream sample uses v0.1.0-alpha), so the
117
+ // ensure step must opt into prerelease discovery for now. Revisit/remove
118
+ // -Prerelease once a stable module exists so future alphas are not preferred.
119
+ const resource = {
120
+ name: WINDOWS_SETTINGS_MODULE_COMMAND_NAME,
121
+ resourceType: RUN_COMMAND_ON_SET_TYPE,
122
+ properties: {
123
+ executable: "pwsh",
124
+ arguments: {
125
+ "0": "-NoProfile",
126
+ "1": "-NoLogo",
127
+ "2": "-Command",
128
+ "3": [
129
+ "$ErrorActionPreference = 'Stop';",
130
+ "if (-not (Get-Module -ListAvailable -Name Microsoft.Windows.Settings)) {",
131
+ " Install-PSResource -Name Microsoft.Windows.Settings -Prerelease -TrustRepository -AcceptLicense | Out-Null",
132
+ "}",
133
+ ].join(" "),
134
+ treatAsArray: true,
135
+ },
136
+ },
137
+ };
138
+ Object.defineProperty(resource, "token", {
139
+ value: Symbol("winix.windows-settings-module"),
140
+ enumerable: false,
141
+ configurable: true,
142
+ });
143
+ return resource;
144
+ }
145
+ const WINDOWS_ENV_TOKEN = /%([^%]+)%/g;
146
+ function canonicalEnvName(name) {
147
+ return name.toLocaleUpperCase("en-US");
148
+ }
149
+ function resolveManagedEnvironmentReferences(resources) {
150
+ if (resources.length === 0)
151
+ return [];
152
+ const managedEnv = new Map();
153
+ for (const resource of resources) {
154
+ const metadata = resource.winix;
155
+ if (metadata?.kind === "env" && metadata.action === "set") {
156
+ managedEnv.set(canonicalEnvName(metadata.name), {
157
+ name: metadata.name,
158
+ value: metadata.value ?? "",
159
+ });
160
+ }
161
+ }
162
+ if (managedEnv.size === 0)
163
+ return [...resources];
164
+ const resolvedEnv = new Map();
165
+ const resolveEnv = (key, stack) => {
166
+ const cached = resolvedEnv.get(key);
167
+ if (cached !== undefined)
168
+ return cached;
169
+ const entry = managedEnv.get(key);
170
+ if (!entry)
171
+ return `%${key}%`;
172
+ const nextStack = [...stack, key];
173
+ const resolved = entry.value.replace(WINDOWS_ENV_TOKEN, (token, name) => {
174
+ const depKey = canonicalEnvName(name);
175
+ if (!managedEnv.has(depKey))
176
+ return token;
177
+ const cycleStart = nextStack.indexOf(depKey);
178
+ if (cycleStart !== -1) {
179
+ const cycle = [...nextStack.slice(cycleStart), depKey]
180
+ .map((cycleKey) => managedEnv.get(cycleKey)?.name ?? cycleKey)
181
+ .join(" -> ");
182
+ throw new Error(`Circular Windows environment variable reference: ${cycle}`);
183
+ }
184
+ return resolveEnv(depKey, nextStack);
185
+ });
186
+ resolvedEnv.set(key, resolved);
187
+ return resolved;
188
+ };
189
+ for (const key of managedEnv.keys()) {
190
+ resolveEnv(key, []);
191
+ }
192
+ const resolveString = (value) => value.replace(WINDOWS_ENV_TOKEN, (token, name) => {
193
+ const key = canonicalEnvName(name);
194
+ return managedEnv.has(key) ? resolveEnv(key, []) : token;
195
+ });
196
+ return resources.map((resource) => {
197
+ const metadata = resource.winix;
198
+ if (metadata?.kind === "env" && metadata.action === "set") {
199
+ const resolvedValue = resolveString(metadata.value ?? "");
200
+ const properties = rewriteEnvValue(resource.properties, resolvedValue);
201
+ return cloneDscResource(resource, properties);
202
+ }
203
+ if (metadata?.kind === "path") {
204
+ const resolvedValue = resolveString(metadata.value);
205
+ if (resolvedValue === metadata.value)
206
+ return resource;
207
+ const properties = rewritePathValue(resource.properties, metadata.value, resolvedValue);
208
+ return cloneDscResource(resource, properties);
209
+ }
210
+ return resource;
211
+ });
212
+ }
213
+ function rewriteEnvValue(properties, value) {
214
+ if (!properties)
215
+ return properties;
216
+ const valueData = properties.valueData;
217
+ if (!valueData || typeof valueData !== "object" || Array.isArray(valueData)) {
218
+ return properties;
219
+ }
220
+ return {
221
+ ...properties,
222
+ valueData: {
223
+ ...valueData,
224
+ String: value,
225
+ },
226
+ };
227
+ }
228
+ function rewritePathValue(properties, originalValue, resolvedValue) {
229
+ if (!properties)
230
+ return properties;
231
+ const original = psSingleQuoted(originalValue);
232
+ const resolved = psSingleQuoted(resolvedValue);
233
+ const rewritten = {};
234
+ for (const [key, value] of Object.entries(properties)) {
235
+ rewritten[key] = rewritePathPropertyValue(value, original, resolved);
236
+ }
237
+ return rewritten;
238
+ }
239
+ function rewritePathPropertyValue(value, original, resolved) {
240
+ if (typeof value === "string") {
241
+ return value.replaceAll(original, resolved);
242
+ }
243
+ if (Array.isArray(value)) {
244
+ return value.map((entry) => rewritePathPropertyValue(entry, original, resolved));
245
+ }
246
+ if (value && typeof value === "object") {
247
+ const rewritten = {};
248
+ for (const [key, child] of Object.entries(value)) {
249
+ rewritten[key] = rewritePathPropertyValue(child, original, resolved);
250
+ }
251
+ return rewritten;
252
+ }
253
+ return value;
254
+ }
255
+ function cloneDscResource(resource, properties, dependsOn = resource.dependsOn) {
256
+ const cloned = { ...resource, properties };
257
+ if (dependsOn)
258
+ cloned.dependsOn = dependsOn;
259
+ else
260
+ delete cloned.dependsOn;
261
+ if (resource.token) {
262
+ Object.defineProperty(cloned, "token", {
263
+ value: resource.token,
264
+ enumerable: false,
265
+ configurable: true,
266
+ });
267
+ }
268
+ if (resource.winix) {
269
+ Object.defineProperty(cloned, "winix", {
270
+ value: resource.winix,
271
+ enumerable: false,
272
+ configurable: true,
273
+ });
274
+ }
275
+ return cloned;
276
+ }
90
277
  /**
91
278
  * Convert an arbitrary identifier into a DSC v3 instance name, which the schema
92
279
  * restricts to `^[a-zA-Z0-9 ]+$` (letters, numbers, spaces only). Non-matching
@@ -166,10 +353,13 @@ function assignResourceNames(hostName, packages, commands, dscResources) {
166
353
  return plan;
167
354
  }
168
355
  /**
169
- * Resolve a resource's `dependsOn` references into DSC v3 `resourceId()`
170
- * lookup strings. Throws when a referenced resource is not present in this
171
- * host's naming plan, which happens if a handle from another host is passed to
172
- * `dependsOn` (cross-host ordering is not expressible in a single document).
356
+ * Resolve a resource's `dependsOn` references into WinGet Configuration
357
+ * instance names. The underlying DSC v3 schema documents `resourceId(...)`
358
+ * lookups, but `winget configure`'s dscv3 processor currently resolves
359
+ * dependencies by simple resource name. Throws when a referenced resource is
360
+ * not present in this host's naming plan, which happens if a handle from
361
+ * another host is passed to `dependsOn` (cross-host ordering is not expressible
362
+ * in a single document).
173
363
  */
174
364
  function resolveDependsOnRefs(refs, naming) {
175
365
  if (!refs || refs.length === 0)
@@ -195,7 +385,7 @@ function resolveDependsOnRefs(refs, naming) {
195
385
  `"${naming.hostName}". Resources can only depend on other resources ` +
196
386
  `within the same host.`);
197
387
  }
198
- ids.push(`[resourceId('${target.type}', '${target.name}')]`);
388
+ ids.push(target.name);
199
389
  }
200
390
  return ids;
201
391
  }
@@ -266,6 +456,10 @@ function renderRawCommandResource(command, plan, naming) {
266
456
  */
267
457
  function renderDscResource(resource, plan, naming) {
268
458
  const out = [];
459
+ if (resource.winix?.kind === "setting") {
460
+ out.push(" # Some Windows settings (including DeveloperMode) require");
461
+ out.push(" # running winget configure from an elevated shell to change.");
462
+ }
269
463
  out.push(` - name: ${yamlScalar(plan.name)}`);
270
464
  out.push(` type: ${yamlScalar(resource.resourceType)}`);
271
465
  const deps = resolveDependsOnRefs(resource.dependsOn, naming);
@@ -287,6 +481,11 @@ function renderDscResource(resource, plan, naming) {
287
481
  }
288
482
  }
289
483
  }
484
+ if (resource.elevated) {
485
+ out.push(` metadata:`);
486
+ out.push(` winget:`);
487
+ out.push(` securityContext: elevated`);
488
+ }
290
489
  return out;
291
490
  }
292
491
  function generateApplyScript() {
@@ -340,3 +539,6 @@ function yamlQuoted(value) {
340
539
  function yamlStringArray(values) {
341
540
  return `[${values.map((value) => yamlQuoted(value)).join(", ")}]`;
342
541
  }
542
+ function psSingleQuoted(value) {
543
+ return `'${value.replace(/'/g, "''")}'`;
544
+ }
@@ -77,6 +77,13 @@ export function yamlEntry(key, value, depth) {
77
77
  }
78
78
  return out;
79
79
  }
80
+ if (typeof value === "string" && /[\r\n]/.test(value)) {
81
+ const childPad = INDENT.repeat(depth + 1);
82
+ return [
83
+ `${pad}${k}: |-`,
84
+ ...value.replace(/\r\n/g, "\n").replace(/\r/g, "\n").split("\n").map((line) => `${childPad}${line}`),
85
+ ];
86
+ }
80
87
  return [`${pad}${k}: ${yamlScalar(value)}`];
81
88
  }
82
89
  /**
@@ -24,7 +24,16 @@ export interface EscapeReportItem {
24
24
  path: string;
25
25
  kind: "escape" | "raw" | "rawModule";
26
26
  }
27
+ export interface SuspiciousNixReference {
28
+ host: string;
29
+ fragment: string;
30
+ scope: string;
31
+ path: string;
32
+ reference: string;
33
+ recommendation: string;
34
+ }
27
35
  export declare function analyzeWorkspace(workspace: WorkspaceDef): HostAnalysis[];
28
36
  export declare function findDuplicateHosts(workspace: WorkspaceDef): string[];
29
37
  export declare function detectConflicts(analyses: HostAnalysis[]): Conflict[];
30
38
  export declare function collectEscapeReport(analyses: HostAnalysis[]): EscapeReportItem[];
39
+ export declare function collectSuspiciousNixReferences(analyses: HostAnalysis[]): SuspiciousNixReference[];
@@ -64,6 +64,20 @@ export function collectEscapeReport(analyses) {
64
64
  }
65
65
  return items;
66
66
  }
67
+ export function collectSuspiciousNixReferences(analyses) {
68
+ const items = [];
69
+ for (const analysis of analyses) {
70
+ for (const record of analysis.fragments) {
71
+ for (const scope of ["nixos", "homeManager", "darwin"]) {
72
+ const data = record.fragment[scope];
73
+ if (!data)
74
+ continue;
75
+ collectSuspiciousReferenceItems(analysis.name, record.label, scope, [], data, items);
76
+ }
77
+ }
78
+ }
79
+ return items;
80
+ }
67
81
  function analyzeHost(host) {
68
82
  const platform = host.platform.__id;
69
83
  const activeIds = collectActiveIds(host);
@@ -145,6 +159,50 @@ function collectEscapeItems(host, fragment, scope, path, value, out) {
145
159
  collectEscapeItems(host, fragment, scope, [...path, key], child, out);
146
160
  }
147
161
  }
162
+ function collectSuspiciousReferenceItems(host, fragment, scope, path, value, out) {
163
+ if (isNixExpr(value) || isRawModuleRef(value))
164
+ return;
165
+ if (typeof value === "string") {
166
+ const references = [...value.matchAll(/\$\{((?:config|pkgs|lib)\.[A-Za-z_][A-Za-z0-9_'.-]*)\}/g)];
167
+ for (const match of references) {
168
+ const reference = match[1];
169
+ out.push({
170
+ host,
171
+ fragment,
172
+ scope,
173
+ path: path.join(".") || "<root>",
174
+ reference,
175
+ recommendation: recommendNixHelper(value, match[0], reference),
176
+ });
177
+ }
178
+ return;
179
+ }
180
+ if (Array.isArray(value)) {
181
+ value.forEach((item, index) => collectSuspiciousReferenceItems(host, fragment, scope, [...path, String(index)], item, out));
182
+ return;
183
+ }
184
+ if (!isPlainObject(value))
185
+ return;
186
+ for (const [key, child] of Object.entries(value)) {
187
+ if (key === "__raw")
188
+ continue;
189
+ collectSuspiciousReferenceItems(host, fragment, scope, [...path, key], child, out);
190
+ }
191
+ }
192
+ function recommendNixHelper(value, interpolation, reference) {
193
+ const homePath = /^\$\{config\.home\.homeDirectory\}\/(.*)$/.exec(value);
194
+ if (homePath) {
195
+ return `Use nix.homePath(${JSON.stringify(homePath[1])}).`;
196
+ }
197
+ const packagePath = /^\$\{pkgs\.([A-Za-z_][A-Za-z0-9_'.-]*)\}\/(.*)$/.exec(value);
198
+ if (packagePath) {
199
+ return `Use nix.pkgPath(${JSON.stringify(packagePath[1])}, ${JSON.stringify(packagePath[2])}).`;
200
+ }
201
+ if (value === interpolation) {
202
+ return `Use nix.expr(${JSON.stringify(reference)}).`;
203
+ }
204
+ return "Use nix.str with nix.expr() interpolation, or nix.expr() for a complete Nix expression.";
205
+ }
148
206
  function formatValue(value) {
149
207
  if (isNixExpr(value))
150
208
  return value.expr;
@@ -1,6 +1,14 @@
1
+ import { type NixOutput } from "../../backends/nix/index.js";
1
2
  interface CheckOptions {
2
3
  strict: boolean;
3
4
  escapeReport: boolean;
4
5
  }
5
6
  export declare function check(cwd: string, opts: CheckOptions): Promise<void>;
7
+ interface NixParseResult {
8
+ error?: NodeJS.ErrnoException;
9
+ status: number | null;
10
+ stderr: string;
11
+ }
12
+ type NixParser = (source: string) => NixParseResult;
13
+ export declare function validateGeneratedNixSyntax(output: NixOutput, parse?: NixParser): void;
6
14
  export {};
@@ -1,16 +1,19 @@
1
1
  // winix check — validate configuration
2
+ import { spawnSync } from "node:child_process";
2
3
  import { loadWorkspace } from "../loader.js";
3
4
  import { evaluate } from "../../evaluator/index.js";
4
5
  import { generateNix } from "../../backends/nix/index.js";
5
- import { analyzeWorkspace, collectEscapeReport, detectConflicts, findDuplicateHosts, } from "../analysis.js";
6
+ import { analyzeWorkspace, collectEscapeReport, collectSuspiciousNixReferences, detectConflicts, findDuplicateHosts, } from "../analysis.js";
6
7
  export async function check(cwd, opts) {
7
8
  try {
8
9
  const { workspace } = await loadWorkspace(cwd);
9
10
  const duplicateHosts = findDuplicateHosts(workspace);
10
11
  const evaluated = evaluate(workspace);
11
12
  const output = generateNix(workspace, evaluated);
13
+ validateGeneratedNixSyntax(output);
12
14
  const analyses = analyzeWorkspace(workspace);
13
15
  const conflicts = detectConflicts(analyses);
16
+ const suspiciousReferences = collectSuspiciousNixReferences(analyses);
14
17
  console.log(`✓ Configuration valid`);
15
18
  console.log(` Hosts: ${evaluated.map((h) => h.name).join(", ")}`);
16
19
  for (const warning of output.warnings) {
@@ -27,6 +30,14 @@ export async function check(cwd, opts) {
27
30
  `${conflict.secondFragment} (${conflict.secondValue})`);
28
31
  }
29
32
  }
33
+ if (suspiciousReferences.length > 0) {
34
+ console.warn(`Warning: ${suspiciousReferences.length} suspicious literal Nix reference(s):`);
35
+ for (const item of suspiciousReferences) {
36
+ console.warn(` ${item.host} ${item.fragment} ${item.scope}.${item.path}: ` +
37
+ `plain string contains \${${item.reference}}`);
38
+ console.warn(` ${item.recommendation}`);
39
+ }
40
+ }
30
41
  if (opts.escapeReport) {
31
42
  const report = collectEscapeReport(analyses);
32
43
  console.log(`\nEscape hatch report: ${report.length} item(s)`);
@@ -44,3 +55,26 @@ export async function check(cwd, opts) {
44
55
  process.exit(1);
45
56
  }
46
57
  }
58
+ export function validateGeneratedNixSyntax(output, parse = parseNixSource) {
59
+ const sources = [
60
+ ["flake.nix", output["flake.nix"]],
61
+ ...Object.entries(output.hosts).map(([name, source]) => [`hosts/${name}`, source]),
62
+ ];
63
+ for (const [name, source] of sources) {
64
+ const result = parse(source);
65
+ if (result.error?.code === "ENOENT")
66
+ return;
67
+ if (result.error)
68
+ throw result.error;
69
+ if (result.status !== 0) {
70
+ const detail = result.stderr.trim() || `nix-instantiate exited with status ${result.status}`;
71
+ throw new Error(`Generated Nix syntax is invalid in ${name}:\n${detail}`);
72
+ }
73
+ }
74
+ }
75
+ function parseNixSource(source) {
76
+ return spawnSync("nix-instantiate", ["--parse", "-"], {
77
+ input: source,
78
+ encoding: "utf8",
79
+ });
80
+ }
@@ -1,5 +1,5 @@
1
1
  import type { ProgramOptions, ServiceOptions } from "./options.js";
2
- import type { Fragment } from "../core/types.js";
2
+ import type { Fragment, NixExpr } from "../core/types.js";
3
3
  import type { HomeFile, HomeOptions, PackageRef } from "../types/index.js";
4
4
  /**
5
5
  * Map of Home Manager program names to their option types.
@@ -19,9 +19,9 @@ export interface HomeHelper {
19
19
  imports(...imports: string[]): Fragment;
20
20
  program<const K extends string>(name: K, opts?: ProgramOptions<HomeProgramOptions, K>): Fragment;
21
21
  service<const K extends string>(name: K, opts?: ServiceOptions<HomeServiceOptions, K>): Fragment;
22
- env(vars: Record<string, string>): Fragment;
23
- path(paths: string[]): Fragment;
24
- path(...paths: string[]): Fragment;
22
+ env(vars: Record<string, string | NixExpr>): Fragment;
23
+ path(paths: (string | NixExpr)[]): Fragment;
24
+ path(...paths: (string | NixExpr)[]): Fragment;
25
25
  packages(packages: PackageRef[]): Fragment;
26
26
  packages(...packages: PackageRef[]): Fragment;
27
27
  files(files: Record<string, HomeFile>): Fragment;
@@ -1,4 +1,5 @@
1
1
  import { normalizeArgs } from "./utils.js";
2
+ import { escapeNixDoubleQuoted, nixStringLiteral } from "../nix/serialize.js";
2
3
  export const home = Object.assign((config) => ({ homeManager: config }), {
3
4
  program: (name, opts = {}) => ({
4
5
  homeManager: { programs: { [name]: { enable: true, ...opts } } },
@@ -37,7 +38,7 @@ export const home = Object.assign((config) => ({ homeManager: config }), {
37
38
  raw: (config) => ({ homeManager: { __raw: [config] } }),
38
39
  activation: (name, opts) => {
39
40
  const after = opts.after ?? ["writeBoundary"];
40
- const afterList = after.map((s) => JSON.stringify(s)).join(" ");
41
+ const afterList = after.map((s) => nixStringLiteral(s)).join(" ");
41
42
  return {
42
43
  homeManager: {
43
44
  home: {
@@ -54,10 +55,7 @@ export const home = Object.assign((config) => ({ homeManager: config }), {
54
55
  });
55
56
  function homePathToNixString(path) {
56
57
  if (path.startsWith("~/")) {
57
- return `"${escapeNixString(`\${config.home.homeDirectory}/${path.slice(2)}`)}"`;
58
+ return '"${config.home.homeDirectory}/' + escapeNixDoubleQuoted(path.slice(2)) + '"';
58
59
  }
59
- return JSON.stringify(path);
60
- }
61
- function escapeNixString(value) {
62
- return value.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
60
+ return nixStringLiteral(path);
63
61
  }
@@ -13,4 +13,4 @@ export type { NixosHelper, NixosProgramOptions, NixosServiceOptions, SysctlSetti
13
13
  export { darwin } from "./darwin.js";
14
14
  export type { DarwinHelper, DarwinProgramOptions, DarwinServiceOptions, LaunchdHelper } from "./darwin.js";
15
15
  export { windows } from "./windows.js";
16
- export type { WindowsHelper, WinDscSpec, WinEnvNamespace, WinEnvOpts, WinEnvScope, WinPackageArg, WinPackageSpec, WinPathNamespace, WinRawCommandArg, WinRawCommandSpec, } from "./windows.js";
16
+ export type { WindowsHelper, WinDscSpec, WinEnvNamespace, WinEnvOpts, WinEnvScope, WinFileEncoding, WinFileNamespace, WinFileOpts, WinPackageArg, WinPackageSpec, WinPathNamespace, WinRawCommandArg, WinRawCommandSpec, WinSettingOpts, } from "./windows.js";
@@ -6,6 +6,16 @@ export interface NixNamespace {
6
6
  expr(expr: string): NixExpr;
7
7
  pkg: PkgHelper;
8
8
  bin(packageName: string, executable: string): NixExpr;
9
+ /**
10
+ * Build a safely quoted path below `config.home.homeDirectory`.
11
+ * Leading `/` characters are ignored; other characters are preserved.
12
+ */
13
+ homePath(relativePath: string): NixExpr;
14
+ /**
15
+ * Build a safely quoted path below `pkgs.<packageName>`.
16
+ * Leading `/` characters are ignored; other characters are preserved.
17
+ */
18
+ pkgPath(packageName: string, relativePath: string): NixExpr;
9
19
  str(strings: TemplateStringsArray, ...values: NixStringPart[]): NixExpr;
10
20
  script: ScriptHelper;
11
21
  concat(...parts: NixStringPart[]): NixExpr;