@adrifer/winix 0.2.0-preview.0 → 0.2.0-preview.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.
@@ -20,6 +20,7 @@ export async function switchCommand(cwd, opts) {
20
20
  host: hostName,
21
21
  dry: false,
22
22
  diff: false,
23
+ windowsLockDry: opts.dry,
23
24
  });
24
25
  const activationTarget = platform === "windows"
25
26
  ? windowsConfigurationForHost(result.outDir, hostName)
@@ -1,6 +1,9 @@
1
+ import { type WindowsPackageVersionResolver } from "../../backends/windows/lockfile.js";
1
2
  interface UpdateOptions {
2
3
  inputs: string[];
3
4
  dry: boolean;
5
+ windows?: boolean;
6
+ resolveWindowsPackageVersion?: WindowsPackageVersionResolver;
4
7
  }
5
8
  export declare function update(cwd: string, opts: UpdateOptions): Promise<void>;
6
9
  export declare function assertUpdateSupported(osPlatform?: NodeJS.Platform): void;
@@ -1,23 +1,35 @@
1
1
  import { join } from "node:path";
2
2
  import { tmpdir } from "node:os";
3
3
  import { cp, mkdtemp, readFile, rename, rm, writeFile } from "node:fs/promises";
4
+ import { evaluate } from "../../evaluator/index.js";
5
+ import { emptyWindowsLock, readWindowsLock, reconcileInlinePins, resolveWindowsLockEntries, windowsLockChanged, writeWindowsLock, } from "../../backends/windows/lockfile.js";
6
+ import { isWindowsHost } from "../../backends/windows/index.js";
7
+ import { assertWingetResolutionSupported, resolveWingetVersion, } from "../../backends/windows/resolver.js";
8
+ import { platformForEvaluatedHost } from "../activation.js";
9
+ import { loadWorkspace } from "../loader.js";
4
10
  import { runCommand } from "../run.js";
5
11
  import { applyWorkspace } from "./apply.js";
6
12
  export async function update(cwd, opts) {
13
+ if (opts.windows) {
14
+ await updateWindowsLock(cwd, opts);
15
+ return;
16
+ }
7
17
  if (!opts.dry) {
8
18
  assertUpdateSupported();
9
19
  }
10
- const result = await applyWorkspace(cwd, { dry: false, diff: false });
11
20
  // `winix update` resolves the Nix flake lock. A Windows-only workspace has
12
21
  // no flake.nix, so there is nothing to update; fail clearly instead of
13
22
  // letting `nix flake update` error out generically.
14
- const hasNixHost = [...result.hostPlatforms.values()].some((platform) => platform !== "windows");
23
+ const { workspace } = await loadWorkspace(cwd);
24
+ const evaluated = evaluate(workspace);
25
+ const hasNixHost = evaluated.some((host) => platformForEvaluatedHost(host) !== "windows");
15
26
  if (!hasNixHost) {
16
27
  throw new Error("`winix update` updates the Nix flake lock, but this workspace has no " +
17
28
  "NixOS or nix-darwin hosts (Windows packages are pinned via " +
18
29
  "`winix-windows.lock`, resolved by a future `winix` milestone). " +
19
30
  "Nothing to update.");
20
31
  }
32
+ const result = await applyWorkspace(cwd, { dry: false, diff: false });
21
33
  const updateDir = await mkdtemp(join(tmpdir(), "winix-update-"));
22
34
  await cp(result.outDir, updateDir, { recursive: true });
23
35
  const args = [
@@ -44,6 +56,115 @@ export async function update(cwd, opts) {
44
56
  await rm(updateDir, { recursive: true, force: true });
45
57
  }
46
58
  }
59
+ async function updateWindowsLock(cwd, opts) {
60
+ const { workspace, configDir } = await loadWorkspace(cwd);
61
+ const evaluated = evaluate(workspace);
62
+ const windowsHosts = evaluated.filter(isWindowsHost);
63
+ if (windowsHosts.length === 0) {
64
+ throw new Error("`winix update --windows` found no Windows hosts in this workspace.");
65
+ }
66
+ if (!opts.resolveWindowsPackageVersion) {
67
+ assertWingetResolutionSupported();
68
+ }
69
+ const now = new Date();
70
+ const originalLock = readWindowsLock(configDir) ?? emptyWindowsLock(now);
71
+ const reconciled = reconcileInlinePins(originalLock, windowsHosts, now);
72
+ let lock = {
73
+ ...reconciled,
74
+ packages: { ...reconciled.packages },
75
+ };
76
+ const pinned = collectInlinePinnedPackages(windowsHosts);
77
+ const floating = collectFloatingPackages(windowsHosts, pinned);
78
+ const selected = selectPackagesForUpdate(floating, pinned, opts.inputs);
79
+ const resolveVersion = opts.resolveWindowsPackageVersion ?? resolveWingetVersion;
80
+ let changed = windowsLockChanged(originalLock, reconciled);
81
+ console.log(`Updating winix-windows.lock for ${windowsHosts.length} Windows host(s).`);
82
+ for (const [id, pkg] of pinned) {
83
+ const entry = lock.packages[id];
84
+ console.log(` pinned ${id} ${pkg.source} ${entry?.version ?? pkg.version}`);
85
+ }
86
+ if (selected.size === 0) {
87
+ console.log(" no floating Windows packages to resolve");
88
+ }
89
+ const resolved = resolveWindowsLockEntries(lock, selected.values(), resolveVersion, now);
90
+ lock = resolved.lock;
91
+ changed = changed || resolved.changed;
92
+ for (const resolution of resolved.resolutions) {
93
+ if (resolution.status === "up-to-date") {
94
+ console.log(` up to date ${resolution.id} ${resolution.source} ${resolution.version}`);
95
+ }
96
+ else if (resolution.status === "updated") {
97
+ console.log(` resolved ${resolution.id} ${resolution.source} ` +
98
+ `${resolution.previousVersion} -> ${resolution.version}`);
99
+ }
100
+ else {
101
+ console.log(` resolved ${resolution.id} ${resolution.source} ${resolution.version} (new)`);
102
+ }
103
+ }
104
+ if (!changed) {
105
+ console.log("winix-windows.lock is already up to date.");
106
+ return;
107
+ }
108
+ if (opts.dry) {
109
+ console.log("Dry run: winix-windows.lock would be updated.");
110
+ return;
111
+ }
112
+ writeWindowsLock(configDir, lock);
113
+ console.log("✓ Updated winix-windows.lock");
114
+ }
115
+ function collectInlinePinnedPackages(windowsHosts) {
116
+ const pinned = new Map();
117
+ for (const host of windowsHosts) {
118
+ const win = host.windows;
119
+ for (const pkg of Object.values(win.packages ?? {})) {
120
+ if (pkg.version !== undefined) {
121
+ pinned.set(pkg.id, pkg);
122
+ }
123
+ }
124
+ }
125
+ return pinned;
126
+ }
127
+ function collectFloatingPackages(windowsHosts, pinned) {
128
+ const floating = new Map();
129
+ for (const host of windowsHosts) {
130
+ const win = host.windows;
131
+ for (const pkg of Object.values(win.packages ?? {})) {
132
+ if (pkg.version !== undefined)
133
+ continue;
134
+ const pinnedPkg = pinned.get(pkg.id);
135
+ if (pinnedPkg) {
136
+ if (pinnedPkg.source !== pkg.source) {
137
+ throw new Error(`Windows package "${pkg.id}" is pinned with source "${pinnedPkg.source}" ` +
138
+ `but also declared floating with source "${pkg.source}". Use one source per package id.`);
139
+ }
140
+ continue;
141
+ }
142
+ const existing = floating.get(pkg.id);
143
+ if (existing && existing.source !== pkg.source) {
144
+ throw new Error(`Windows package "${pkg.id}" is declared with multiple sources. ` +
145
+ `Use one source per package id.`);
146
+ }
147
+ floating.set(pkg.id, pkg);
148
+ }
149
+ }
150
+ return floating;
151
+ }
152
+ function selectPackagesForUpdate(floating, pinned, inputs) {
153
+ if (inputs.length === 0)
154
+ return floating;
155
+ const selected = new Map();
156
+ for (const id of inputs) {
157
+ const pkg = floating.get(id);
158
+ if (pkg) {
159
+ selected.set(id, pkg);
160
+ continue;
161
+ }
162
+ if (!pinned.has(id)) {
163
+ throw new Error(`Windows package "${id}" is not declared in this workspace.`);
164
+ }
165
+ }
166
+ return selected;
167
+ }
47
168
  export function assertUpdateSupported(osPlatform = process.platform) {
48
169
  if (osPlatform !== "win32")
49
170
  return;
package/dist/cli/index.js CHANGED
@@ -13,6 +13,7 @@ const { positionals, values } = parseArgs({
13
13
  host: { type: "string" },
14
14
  dry: { type: "boolean", default: false },
15
15
  diff: { type: "boolean", default: false },
16
+ windows: { type: "boolean", default: false },
16
17
  strict: { type: "boolean", default: false },
17
18
  force: { type: "boolean", default: false },
18
19
  "escape-report": { type: "boolean", default: false },
@@ -36,6 +37,7 @@ Options:
36
37
  --host <name> Target a specific host
37
38
  --dry Show what would be generated (apply)
38
39
  --diff Show diff against current output (apply)
40
+ --windows Resolve Windows package lockfile (update)
39
41
  --strict Treat conflicts as errors (check)
40
42
  --escape-report Show escape hatch usage (check)
41
43
  --force Overwrite files (init)
@@ -99,6 +101,7 @@ switch (command) {
99
101
  try {
100
102
  await update(cwd, {
101
103
  dry: values.dry,
104
+ windows: values.windows,
102
105
  inputs: positionals.slice(1),
103
106
  });
104
107
  }
@@ -27,6 +27,34 @@ export interface NixExpr {
27
27
  __winixNixExpr: true;
28
28
  expr: string;
29
29
  }
30
+ /**
31
+ * Identity of a single emittable resource, used to wire `dependsOn` across
32
+ * declarations within one host. Currently only the Windows backend produces
33
+ * resources with handles.
34
+ *
35
+ * - `package`: identified by its natural, stable package id.
36
+ * - `command`: has no natural id, so it carries a unique token; the emitter
37
+ * assigns it a generated name (`command-N`) per host.
38
+ */
39
+ export type ResourceRef = {
40
+ kind: "package";
41
+ id: string;
42
+ } | {
43
+ kind: "command";
44
+ token: symbol;
45
+ };
46
+ /**
47
+ * A resource handle: the value returned by resource-producing helpers like
48
+ * `windows.package(...)` / `windows.raw(...)`.
49
+ *
50
+ * It is a normal Fragment (so it still merges and registers as an effect),
51
+ * decorated with `__winixHandle` so it can be passed to another resource's
52
+ * `dependsOn` to express ordering. The handle is opaque to user code; only the
53
+ * emitter reads `__winixHandle` to resolve dependency references to names.
54
+ */
55
+ export interface ResourceHandle extends Fragment {
56
+ __winixHandle: ResourceRef;
57
+ }
30
58
  export type ImportRef = string | RawModuleRef;
31
59
  /**
32
60
  * What goes into a host/profile fragment list. Arrays are recursive so profiles
@@ -37,6 +65,23 @@ export type FragmentEntry = LazyFragment | Fragment | readonly FragmentEntry[];
37
65
  * What a lazy fragment can resolve into.
38
66
  */
39
67
  export type FragmentResult = FragmentEntry;
68
+ /**
69
+ * The return type allowed for *authoring callbacks* (`feature`/`profile`/`host`
70
+ * bodies). It is a `FragmentResult` OR nothing (`void`/`undefined`), because a
71
+ * callback may declare purely by effect through the injected namespaces and
72
+ * return nothing at all:
73
+ *
74
+ * ```ts
75
+ * feature("dev", ({ home }) => { home.program("git"); }); // returns void
76
+ * ```
77
+ *
78
+ * The runtime already treats a `undefined`/`null` return as "no returned
79
+ * content" and falls back to the collected effects (see
80
+ * `mergeEffectsAndReturn`); this type makes the public signatures match that
81
+ * behavior. `FragmentResult` itself stays strict for internal use where a
82
+ * concrete result is always present.
83
+ */
84
+ export type AuthoringResult = FragmentResult | void;
40
85
  /**
41
86
  * A lazy fragment descriptor: holds the factory + args for deferred evaluation.
42
87
  */
@@ -47,11 +47,20 @@ function evaluateHost(host) {
47
47
  result.darwin = deepMerge(result.darwin, fragment.darwin);
48
48
  }
49
49
  if (fragment.windows && shouldMergeScope(resolvedFragments, "windows")) {
50
- result.windows = deepMerge(result.windows, fragment.windows);
50
+ result.windows = mergeWindowsOptions(result.windows, fragment.windows);
51
51
  }
52
52
  }
53
53
  return result;
54
54
  }
55
+ function mergeWindowsOptions(target, source) {
56
+ const targetCommands = Array.isArray(target.commands) ? target.commands : [];
57
+ const sourceCommands = Array.isArray(source.commands) ? source.commands : [];
58
+ const result = deepMerge(target, source);
59
+ if (targetCommands.length > 0 || sourceCommands.length > 0) {
60
+ result.commands = [...targetCommands, ...sourceCommands];
61
+ }
62
+ return result;
63
+ }
55
64
  function shouldMergeScope(fragments, scope) {
56
65
  const platformFragments = fragments.filter((fragment) => fragment.__platform);
57
66
  if (platformFragments.length === 0)
@@ -2,13 +2,13 @@ import { feature, getEvalContext } from "../sdk/index.js";
2
2
  import { nix } from "./nix.js";
3
3
  export const account = {
4
4
  user: (name, factory) => {
5
- const fn = feature(`account:user:${name}`, (...args) => accountFragment(name, factory(...args)));
5
+ const fn = feature(`account:user:${name}`, (_ctx, ...args) => accountFragment(name, factory(...args)));
6
6
  defineMetadata(fn, "name", name);
7
7
  defineMetadata(fn, "kind", "account.user");
8
8
  return fn;
9
9
  },
10
10
  group: (name, factory = (() => ({}))) => {
11
- const fn = feature(`account:group:${name}`, (...args) => groupFragment(name, factory(...args)));
11
+ const fn = feature(`account:group:${name}`, (_ctx, ...args) => groupFragment(name, factory(...args)));
12
12
  defineMetadata(fn, "name", name);
13
13
  defineMetadata(fn, "kind", "account.group");
14
14
  return fn;
@@ -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, WinPackageArg, WinPackageSpec } from "./windows.js";
16
+ export type { WindowsHelper, WinPackageArg, WinPackageSpec, WinRawCommandArg, WinRawCommandSpec } from "./windows.js";
@@ -1,4 +1,4 @@
1
- import type { Fragment } from "../core/types.js";
1
+ import type { ResourceHandle } from "../core/types.js";
2
2
  import type { WinPackageSource } from "../types/index.js";
3
3
  /**
4
4
  * Accepted call shapes for `windows.package(...)`.
@@ -11,8 +11,28 @@ export interface WinPackageSpec {
11
11
  source?: WinPackageSource;
12
12
  version?: string;
13
13
  elevated?: boolean;
14
+ /**
15
+ * Resources this package must be applied after. Accepts a single handle or
16
+ * an array of handles, both returned by `windows.package(...)` /
17
+ * `windows.raw(...)`.
18
+ */
19
+ dependsOn?: ResourceHandle | ResourceHandle[];
14
20
  }
15
21
  export type WinPackageArg = string | WinPackageSpec;
22
+ /**
23
+ * Accepted object shape for `windows.raw(...)`.
24
+ */
25
+ export interface WinRawCommandSpec {
26
+ name?: string;
27
+ executable: string;
28
+ arguments?: string[];
29
+ /**
30
+ * Resources this command must run after. Accepts a single handle or an array
31
+ * of handles.
32
+ */
33
+ dependsOn?: ResourceHandle | ResourceHandle[];
34
+ }
35
+ export type WinRawCommandArg = string | WinRawCommandSpec;
16
36
  export interface WindowsHelper {
17
37
  /**
18
38
  * Declare a winget/msstore package.
@@ -23,6 +43,21 @@ export interface WindowsHelper {
23
43
  * windows.package({ id: "Git.Git", version: "2.44.0" })
24
44
  * ```
25
45
  */
26
- package(arg: WinPackageArg): Fragment;
46
+ package(arg: WinPackageArg): ResourceHandle;
47
+ /**
48
+ * Run an arbitrary command on every Windows apply via DSC v3's
49
+ * `Microsoft.DSC.Transitional/RunCommandOnSet` resource.
50
+ *
51
+ * This is an escape hatch, not a declarative/idempotent helper:
52
+ * `RunCommandOnSet` has no real test phase, so the command runs on every
53
+ * `winget configure` apply. Prefer typed helpers when available.
54
+ *
55
+ * ```ts
56
+ * windows.raw("New-Item -ItemType Directory -Force -Path $env:USERPROFILE\\.local\\bin")
57
+ * windows.raw({ executable: "pwsh", arguments: ["-Command", "Write-Host hi"] })
58
+ * windows.raw({ name: "make-bin-dir", executable: "cmd", arguments: ["/c", "mkdir", "foo"] })
59
+ * ```
60
+ */
61
+ raw(arg: WinRawCommandArg): ResourceHandle;
27
62
  }
28
63
  export declare const windows: WindowsHelper;
@@ -1,8 +1,32 @@
1
1
  // Windows helper namespace: `windows.*` authoring surface.
2
2
  //
3
- // MVP vertical slice: only `windows.package(...)`. Mirrors the shape and
3
+ // MVP vertical slice: packages plus raw commands. Mirrors the shape and
4
4
  // naming of the `nixos.*` / `darwin.*` namespaces. Additional helpers
5
- // (env, path, file, raw, dsc, wsl, programs) land in follow-up milestones.
5
+ // (env, path, file, dsc, wsl, programs) land in follow-up milestones.
6
+ /**
7
+ * Resolve `dependsOn` (a single handle or an array) into the stable resource
8
+ * references the emitter wires up. Throws on a value that is not a Winix
9
+ * resource handle (e.g. a plain fragment or a handle from a non-resource
10
+ * helper), since only resources can be ordered.
11
+ */
12
+ function resolveDependsOn(dependsOn) {
13
+ if (!dependsOn)
14
+ return undefined;
15
+ const handles = Array.isArray(dependsOn) ? dependsOn : [dependsOn];
16
+ if (handles.length === 0)
17
+ return undefined;
18
+ const refs = [];
19
+ for (const handle of handles) {
20
+ const ref = handle?.__winixHandle;
21
+ if (!ref) {
22
+ throw new Error("windows.*(dependsOn) expects resource handles returned by " +
23
+ "windows.package(...) or windows.raw(...). Got a value without a " +
24
+ "resource identity.");
25
+ }
26
+ refs.push(ref);
27
+ }
28
+ return refs;
29
+ }
6
30
  function normalizePackage(arg) {
7
31
  if (typeof arg === "string") {
8
32
  if (arg.length === 0) {
@@ -29,11 +53,84 @@ function normalizePackage(arg) {
29
53
  if (arg.elevated !== undefined) {
30
54
  pkg.elevated = arg.elevated;
31
55
  }
56
+ const deps = resolveDependsOn(arg.dependsOn);
57
+ if (deps)
58
+ pkg.dependsOn = deps;
32
59
  return pkg;
33
60
  }
61
+ function normalizeRawCommand(arg) {
62
+ if (typeof arg === "string") {
63
+ if (arg.length === 0) {
64
+ throw new Error("windows.raw(command) requires a non-empty command string");
65
+ }
66
+ return withToken({
67
+ executable: "powershell",
68
+ arguments: ["-Command", arg],
69
+ });
70
+ }
71
+ if (!arg || typeof arg !== "object") {
72
+ throw new Error("windows.raw(...) requires a command string or a spec object");
73
+ }
74
+ if (!arg.executable || typeof arg.executable !== "string") {
75
+ throw new Error("windows.raw({ executable }) requires a non-empty executable");
76
+ }
77
+ const command = {
78
+ executable: arg.executable,
79
+ };
80
+ if (arg.name !== undefined) {
81
+ if (typeof arg.name !== "string" || arg.name.length === 0) {
82
+ throw new Error("windows.raw({ name }) must be a non-empty string");
83
+ }
84
+ command.name = arg.name;
85
+ }
86
+ if (arg.arguments !== undefined) {
87
+ if (!Array.isArray(arg.arguments) ||
88
+ arg.arguments.some((value) => typeof value !== "string")) {
89
+ throw new Error("windows.raw({ arguments }) must be an array of strings");
90
+ }
91
+ command.arguments = arg.arguments;
92
+ }
93
+ const deps = resolveDependsOn(arg.dependsOn);
94
+ if (deps)
95
+ command.dependsOn = deps;
96
+ return withToken(command);
97
+ }
98
+ /**
99
+ * Stamp a non-enumerable identity token onto a command so a handle can
100
+ * reference it via `dependsOn`. Non-enumerable so it never shows up in deep
101
+ * equality checks, JSON, or the emitted YAML; it is read only by the helper
102
+ * (to build the handle ref) and the emitter (to resolve names).
103
+ */
104
+ function withToken(command) {
105
+ Object.defineProperty(command, "token", {
106
+ value: Symbol("winix.command"),
107
+ enumerable: false,
108
+ configurable: true,
109
+ });
110
+ return command;
111
+ }
112
+ /**
113
+ * Attach a resource identity to a fragment, turning it into a handle that can
114
+ * be passed to another resource's `dependsOn`. The `__winixHandle` marker is
115
+ * non-enumerable so it never leaks into the merged IR or emitted output.
116
+ */
117
+ function asHandle(fragment, ref) {
118
+ Object.defineProperty(fragment, "__winixHandle", {
119
+ value: ref,
120
+ enumerable: false,
121
+ configurable: true,
122
+ });
123
+ return fragment;
124
+ }
34
125
  export const windows = {
35
126
  package: (arg) => {
36
127
  const pkg = normalizePackage(arg);
37
- return { windows: { packages: { [pkg.id]: pkg } } };
128
+ const fragment = { windows: { packages: { [pkg.id]: pkg } } };
129
+ return asHandle(fragment, { kind: "package", id: pkg.id });
130
+ },
131
+ raw: (arg) => {
132
+ const command = normalizeRawCommand(arg);
133
+ const fragment = { windows: { commands: [command] } };
134
+ return asHandle(fragment, { kind: "command", token: command.token });
38
135
  },
39
136
  };
package/dist/index.d.ts CHANGED
@@ -1,6 +1,7 @@
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, } 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, } from "./types/index.js";
3
3
  export { platform, feature, profile, host, workspace, input, defineInputs, rawModule, withContext } from "./sdk/index.js";
4
+ export type { WinixContext } from "./sdk/context.js";
4
5
  export { evaluate } from "./evaluator/index.js";
5
6
  export type { EvaluatedHost } from "./evaluator/index.js";
6
7
  export { generateNix } from "./backends/nix/index.js";
@@ -8,4 +9,4 @@ export type { NixOutput } from "./backends/nix/index.js";
8
9
  export { generateWindows, isWindowsHost } from "./backends/windows/index.js";
9
10
  export type { WindowsOutput, WindowsHostOutput } from "./backends/windows/index.js";
10
11
  export { account, darwin, home, nix, nixos, overlay, platforms, windows } from "./helpers/index.js";
11
- 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, WinPackageArg, WinPackageSpec } 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, WinPackageArg, WinPackageSpec, WinRawCommandArg, WinRawCommandSpec } from "./helpers/index.js";
@@ -0,0 +1,22 @@
1
+ import type { Fragment } from "../core/types.js";
2
+ /**
3
+ * Run `fn` with a fresh effect sink active, returning the fragments declared by
4
+ * effect during the call (in declaration order). Nesting is supported: an inner
5
+ * `withCollector` does not leak into the outer sink.
6
+ */
7
+ export declare function withCollector(fn: () => void): Fragment[];
8
+ /**
9
+ * Register a fragment as an effect on the active sink, if any. Returns the same
10
+ * fragment so callers can both register and return it. No-op (returns the value
11
+ * unchanged) when there is no active sink, so global usage outside a body keeps
12
+ * working untouched.
13
+ */
14
+ export declare function collect<T extends Fragment>(fragment: T): T;
15
+ /**
16
+ * Whether `value` was already registered by effect on the active sink. Used by
17
+ * the evaluator to skip a returned fragment that was also collected, preventing
18
+ * duplicates when a body both calls a helper and returns its result.
19
+ */
20
+ export declare function wasCollected(value: unknown): boolean;
21
+ /** Whether an effect sink is currently active (a body is being resolved). */
22
+ export declare function hasActiveCollector(): boolean;
@@ -0,0 +1,70 @@
1
+ // Effect-registration collector (layer 2 of the context-injection proposal).
2
+ //
3
+ // The legacy model is return-based: a unit body returns a FragmentResult and
4
+ // the evaluator walks it. Effect registration lets a body *declare by calling*:
5
+ //
6
+ // feature("dev", ({ home, windows }) => {
7
+ // home.program("git"); // registered as an effect, no return needed
8
+ // windows.package("Git.Git");
9
+ // });
10
+ //
11
+ // Mechanism: a scoped stack of "sinks". `withCollector` pushes a fresh sink,
12
+ // runs the body, and pops it, returning everything collected. Each declaration
13
+ // namespace, when called through the injected context, calls `collect(fragment)`
14
+ // to push its result onto the active sink (and remembers the reference).
15
+ //
16
+ // Back-compat with the return forms: a body may still `return` fragments. To
17
+ // avoid double-counting a fragment that is BOTH registered as an effect and
18
+ // returned (e.g. `return home.program(...)`), the evaluator consults
19
+ // `wasCollected(fragment)` and skips return values already captured by effect.
20
+ const G = globalThis;
21
+ function stack() {
22
+ return (G.__winixCollectorStack ??= []);
23
+ }
24
+ function activeSink() {
25
+ const s = stack();
26
+ return s.length > 0 ? s[s.length - 1] : undefined;
27
+ }
28
+ /**
29
+ * Run `fn` with a fresh effect sink active, returning the fragments declared by
30
+ * effect during the call (in declaration order). Nesting is supported: an inner
31
+ * `withCollector` does not leak into the outer sink.
32
+ */
33
+ export function withCollector(fn) {
34
+ const sink = { fragments: [], seen: new WeakSet() };
35
+ stack().push(sink);
36
+ try {
37
+ fn();
38
+ }
39
+ finally {
40
+ stack().pop();
41
+ }
42
+ return sink.fragments;
43
+ }
44
+ /**
45
+ * Register a fragment as an effect on the active sink, if any. Returns the same
46
+ * fragment so callers can both register and return it. No-op (returns the value
47
+ * unchanged) when there is no active sink, so global usage outside a body keeps
48
+ * working untouched.
49
+ */
50
+ export function collect(fragment) {
51
+ const sink = activeSink();
52
+ if (sink && fragment && typeof fragment === "object") {
53
+ sink.fragments.push(fragment);
54
+ sink.seen.add(fragment);
55
+ }
56
+ return fragment;
57
+ }
58
+ /**
59
+ * Whether `value` was already registered by effect on the active sink. Used by
60
+ * the evaluator to skip a returned fragment that was also collected, preventing
61
+ * duplicates when a body both calls a helper and returns its result.
62
+ */
63
+ export function wasCollected(value) {
64
+ const sink = activeSink();
65
+ return !!sink && typeof value === "object" && value !== null && sink.seen.has(value);
66
+ }
67
+ /** Whether an effect sink is currently active (a body is being resolved). */
68
+ export function hasActiveCollector() {
69
+ return activeSink() !== undefined;
70
+ }
@@ -0,0 +1,32 @@
1
+ import type { DarwinHelper } from "../helpers/darwin.js";
2
+ import type { HomeHelper } from "../helpers/home.js";
3
+ import type { NixosHelper } from "../helpers/nixos.js";
4
+ import type { PlatformsHelper } from "../helpers/platforms.js";
5
+ import type { WindowsHelper } from "../helpers/windows.js";
6
+ /**
7
+ * The object injected into the callback form of `feature`, `profile`, and
8
+ * `host`. A single shared shape across all three containers (they all just
9
+ * "contain declarations"); see the context-injection proposal.
10
+ *
11
+ * Holds only the namespaces used to declare a unit's body. Pure utilities
12
+ * (`nix`), top-level constructors (`account`), and array-value helpers
13
+ * (`overlay`) stay as file-level imports by design.
14
+ */
15
+ export interface WinixContext {
16
+ home: HomeHelper;
17
+ nixos: NixosHelper;
18
+ darwin: DarwinHelper;
19
+ windows: WindowsHelper;
20
+ /** Query side: `platforms.darwin.isActive`, etc. (also a platform constructor). */
21
+ platforms: PlatformsHelper;
22
+ }
23
+ /**
24
+ * Build the context object passed to authoring callbacks.
25
+ *
26
+ * Returns references to the same namespace singletons the package exports, so
27
+ * `({ home }) => home.program(...)` and the global `home.program(...)` are
28
+ * interchangeable. Methods called through the context register their Fragment
29
+ * result as an effect when a collector is active (layer 2), while still
30
+ * returning it so the return forms keep working.
31
+ */
32
+ export declare function createWinixContext(): WinixContext;