@adrifer/winix 0.2.0 → 0.2.2

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:
@@ -324,6 +333,53 @@ licenses that aren't a simple `pkgs.lib.licenses.<id>` lookup. See
324
333
  [`spec/proposals/binary-release.md`](spec/proposals/binary-release.md)
325
334
  for the full reference.
326
335
 
336
+ Release assets can also be raw executables. Set `format: "raw"` explicitly;
337
+ Winix never guesses that an extensionless file is executable. The format is
338
+ per-platform, so raw and archive assets can be mixed in one release:
339
+
340
+ ```ts
341
+ home.packages(
342
+ nix.binaryRelease({
343
+ name: "herdr",
344
+ version: "0.8.2",
345
+ binary: "herdr",
346
+ urlTemplate:
347
+ "https://github.com/herdrdev/herdr/releases/download/v{version}/{file}",
348
+ platforms: {
349
+ "x86_64-linux": {
350
+ file: "herdr-linux-x86_64",
351
+ hash: "sha256-...",
352
+ format: "raw",
353
+ },
354
+ "aarch64-linux": {
355
+ file: "herdr-linux-aarch64",
356
+ hash: "sha256-...",
357
+ format: "raw",
358
+ },
359
+ "x86_64-darwin": {
360
+ file: "herdr-macos-x86_64",
361
+ hash: "sha256-...",
362
+ format: "raw",
363
+ },
364
+ "aarch64-darwin": {
365
+ file: "herdr-macos-aarch64",
366
+ hash: "sha256-...",
367
+ format: "raw",
368
+ },
369
+ },
370
+ meta: {
371
+ description: "The runtime your coding agents live on",
372
+ homepage: "https://github.com/herdrdev/herdr",
373
+ license: "asl20",
374
+ },
375
+ }),
376
+ );
377
+ ```
378
+
379
+ When `format` is omitted, `.zip`, `.tar.gz`, and `.tgz` filenames retain the
380
+ legacy extension-based archive behavior. Other extensions are rejected unless
381
+ a supported format (`"raw"`, `"zip"`, `"tar.gz"`, or `"tgz"`) is explicit.
382
+
327
383
  For bigger migrations, import existing Nix modules:
328
384
 
329
385
  ```ts
@@ -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;
@@ -3,7 +3,7 @@ import { spawnSync } from "node:child_process";
3
3
  import { loadWorkspace } from "../loader.js";
4
4
  import { evaluate } from "../../evaluator/index.js";
5
5
  import { generateNix } from "../../backends/nix/index.js";
6
- import { analyzeWorkspace, collectEscapeReport, detectConflicts, findDuplicateHosts, } from "../analysis.js";
6
+ import { analyzeWorkspace, collectEscapeReport, collectSuspiciousNixReferences, detectConflicts, findDuplicateHosts, } from "../analysis.js";
7
7
  export async function check(cwd, opts) {
8
8
  try {
9
9
  const { workspace } = await loadWorkspace(cwd);
@@ -13,6 +13,7 @@ export async function check(cwd, opts) {
13
13
  validateGeneratedNixSyntax(output);
14
14
  const analyses = analyzeWorkspace(workspace);
15
15
  const conflicts = detectConflicts(analyses);
16
+ const suspiciousReferences = collectSuspiciousNixReferences(analyses);
16
17
  console.log(`✓ Configuration valid`);
17
18
  console.log(` Hosts: ${evaluated.map((h) => h.name).join(", ")}`);
18
19
  for (const warning of output.warnings) {
@@ -29,6 +30,14 @@ export async function check(cwd, opts) {
29
30
  `${conflict.secondFragment} (${conflict.secondValue})`);
30
31
  }
31
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
+ }
32
41
  if (opts.escapeReport) {
33
42
  const report = collectEscapeReport(analyses);
34
43
  console.log(`\nEscape hatch report: ${report.length} item(s)`);
@@ -3,7 +3,7 @@ export type { AccountGroupFactory, AccountGroupMember, AccountGroupOpts, Account
3
3
  export { platforms } from "./platforms.js";
4
4
  export type { DarwinPlatformOpts, NixosPlatformOpts, WindowsPlatformOpts, PlatformsHelper } from "./platforms.js";
5
5
  export { nix } from "./nix.js";
6
- export type { BinaryReleaseArch, BinaryReleaseCompletions, BinaryReleaseMeta, BinaryReleaseOpts, BinaryReleasePlatform, NixNamespace, PkgHelper, ScriptHelper, } from "./nix.js";
6
+ export type { BinaryReleaseArch, BinaryReleaseCompletions, BinaryReleaseFormat, BinaryReleaseMeta, BinaryReleaseOpts, BinaryReleasePlatform, NixNamespace, PkgHelper, ScriptHelper, } from "./nix.js";
7
7
  export { overlay } from "./overlay.js";
8
8
  export type { OverlayHelper } from "./overlay.js";
9
9
  export { home } from "./home.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;
@@ -20,8 +30,9 @@ export interface NixNamespace {
20
30
  *
21
31
  * Picks the right `(file, hash)` per `pkgs.stdenv.hostPlatform.system`,
22
32
  * substitutes `{version}`, `{file}`, and (optionally) `{platform}` into
23
- * `urlTemplate`, fetches with `pkgs.fetchurl`, unpacks tarballs/zips,
24
- * and `install -Dm755`s the binary into `$out/bin/<binary>`.
33
+ * `urlTemplate`, fetches with `pkgs.fetchurl`, unpacks tarballs/zips (or
34
+ * directly installs raw executables), and `install -Dm755`s the binary
35
+ * into `$out/bin/<binary>`.
25
36
  *
26
37
  * Optional extensions:
27
38
  * - `completions` — emits `installShellCompletion` for `bash`/`fish`/`zsh`.
@@ -69,11 +80,15 @@ export interface NixNamespace {
69
80
  }
70
81
  /** Supported `(os, arch)` strings for `nix.binaryRelease`. */
71
82
  export type BinaryReleaseArch = "x86_64-linux" | "aarch64-linux" | "x86_64-darwin" | "aarch64-darwin";
83
+ export type BinaryReleaseFormat = "raw" | "zip" | "tar.gz" | "tgz";
72
84
  export interface BinaryReleasePlatform {
73
85
  /** Filename to download (substituted into `urlTemplate`'s `{file}`). */
74
86
  file: string;
75
- /** SRI hash (`sha256-...`) of the downloaded archive. */
87
+ /** SRI hash (`sha256-...`) of the downloaded file. */
76
88
  hash: string;
89
+ /** Download format. When omitted, archive format is inferred from `file`.
90
+ * Raw executables must explicitly set `"raw"`. */
91
+ format?: BinaryReleaseFormat;
77
92
  /** Optional: name of the extracted binary, if it differs from the outer `binary`. */
78
93
  binary?: string;
79
94
  /** Optional: vendor-specific platform tag substituted into `urlTemplate`'s `{platform}`
@@ -3,6 +3,10 @@ const expr = (value) => ({ __winixNixExpr: true, expr: value });
3
3
  const pkg = Object.assign((name) => expr(`pkgs.${name}`), {
4
4
  stable: (name) => expr(`pkgs.stable.${name}`),
5
5
  });
6
+ function pathUnder(base, relativePath) {
7
+ const normalized = relativePath.replace(/^\/+/, "");
8
+ return normalized === "" ? nix.str `${base}` : nix.str `${base}/${normalized}`;
9
+ }
6
10
  const script = Object.assign((first, ...values) => {
7
11
  const body = typeof first === "string"
8
12
  ? first
@@ -24,6 +28,8 @@ export const nix = {
24
28
  expr,
25
29
  pkg,
26
30
  bin: (packageName, executable) => nix.str `${pkg(packageName)}/bin/${executable}`,
31
+ homePath: (relativePath) => pathUnder(expr("config.home.homeDirectory"), relativePath),
32
+ pkgPath: (packageName, relativePath) => pathUnder(pkg(packageName), relativePath),
27
33
  str: (strings, ...values) => {
28
34
  const parts = [];
29
35
  const rawStrings = strings.raw;
@@ -67,6 +73,12 @@ const KNOWN_BINARY_RELEASE_ARCHES = [
67
73
  "x86_64-darwin",
68
74
  "aarch64-darwin",
69
75
  ];
76
+ const KNOWN_BINARY_RELEASE_FORMATS = [
77
+ "raw",
78
+ "zip",
79
+ "tar.gz",
80
+ "tgz",
81
+ ];
70
82
  function binaryRelease(opts) {
71
83
  if (!opts || typeof opts !== "object") {
72
84
  throw new Error("nix.binaryRelease: `opts` is required");
@@ -112,6 +124,7 @@ function binaryRelease(opts) {
112
124
  if (!platform.hash) {
113
125
  throw new Error(`nix.binaryRelease: platforms.${arch}.hash is required`);
114
126
  }
127
+ resolveBinaryReleaseFormat(arch, platform);
115
128
  }
116
129
  const usesPlatformPlaceholder = opts.urlTemplate.includes("{platform}");
117
130
  if (usesPlatformPlaceholder) {
@@ -127,6 +140,7 @@ function binaryRelease(opts) {
127
140
  `file = ${nixStringLiteral(platform.file)};`,
128
141
  `hash = ${nixStringLiteral(platform.hash)};`,
129
142
  `binary = ${nixStringLiteral(platform.binary ?? opts.binary)};`,
143
+ `format = ${nixStringLiteral(resolveBinaryReleaseFormat(arch, platform))};`,
130
144
  ];
131
145
  if (usesPlatformPlaceholder) {
132
146
  const platformName = platform.platform;
@@ -202,14 +216,16 @@ in pkgs.stdenvNoCC.mkDerivation {
202
216
 
203
217
  nativeBuildInputs = ${nativeBuildInputsExpr};${linuxBuildInputs}${dontStripLine}
204
218
 
219
+ dontUnpack = source.format == "raw";
220
+
205
221
  unpackPhase = ''
206
222
  runHook preUnpack
207
223
  mkdir source
208
- case "$src" in
209
- *.zip) unzip -q "$src" -d source ;;
210
- *.tar.gz) tar -xzf "$src" -C source ;;
211
- *.tgz) tar -xzf "$src" -C source ;;
212
- *) echo "nix.binaryRelease: unsupported archive extension for $src" >&2; exit 1 ;;
224
+ case "\${source.format}" in
225
+ zip) unzip -q "$src" -d source ;;
226
+ tar.gz) tar -xzf "$src" -C source ;;
227
+ tgz) tar -xzf "$src" -C source ;;
228
+ *) echo "nix.binaryRelease: unsupported archive format \${source.format}" >&2; exit 1 ;;
213
229
  esac
214
230
  sourceRoot=source
215
231
  runHook postUnpack
@@ -217,7 +233,11 @@ in pkgs.stdenvNoCC.mkDerivation {
217
233
 
218
234
  installPhase = ''
219
235
  runHook preInstall
220
- install -Dm755 "\${source.binary}" "$out/bin/${opts.binary}"${extraInstallBlock}
236
+ installSource="$src"
237
+ if [ "\${source.format}" != raw ]; then
238
+ installSource="\${source.binary}"
239
+ fi
240
+ install -Dm755 "$installSource" "$out/bin/${opts.binary}"${extraInstallBlock}
221
241
  runHook postInstall
222
242
  '';${completionsBlock}
223
243
 
@@ -227,6 +247,21 @@ ${metaLines.join("\n")}
227
247
  })`;
228
248
  return expr(text);
229
249
  }
250
+ function resolveBinaryReleaseFormat(arch, platform) {
251
+ if (platform.format !== undefined) {
252
+ if (!KNOWN_BINARY_RELEASE_FORMATS.includes(platform.format)) {
253
+ throw new Error(`nix.binaryRelease: platforms.${arch}.format must be one of "raw", "zip", "tar.gz", or "tgz"`);
254
+ }
255
+ return platform.format;
256
+ }
257
+ if (platform.file.endsWith(".tar.gz"))
258
+ return "tar.gz";
259
+ if (platform.file.endsWith(".tgz"))
260
+ return "tgz";
261
+ if (platform.file.endsWith(".zip"))
262
+ return "zip";
263
+ throw new Error(`nix.binaryRelease: platforms.${arch}.file has an unsupported archive extension; set \`format\` explicitly`);
264
+ }
230
265
  function renderBuildInput(value) {
231
266
  if (isNixExpr(value))
232
267
  return value.expr;
package/dist/index.d.ts CHANGED
@@ -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, WinFileEncoding, WinFileNamespace, WinFileOpts, WinPackageArg, WinPackageSpec, WinPathNamespace, WinRawCommandArg, WinRawCommandSpec, WinSettingOpts } from "./helpers/index.js";
12
+ 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";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@adrifer/winix",
3
- "version": "0.2.0",
3
+ "version": "0.2.2",
4
4
  "description": "TypeScript-first system configuration for NixOS, nix-darwin, and Home Manager",
5
5
  "license": "MIT",
6
6
  "author": "Adrian Fernandez",