@adrifer/winix 0.2.2 → 0.2.4-preview.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +374 -2
- package/dist/backends/windows/index.d.ts +3 -1
- package/dist/backends/windows/index.js +99 -7
- package/dist/backends/windows/lockfile.d.ts +36 -1
- package/dist/backends/windows/lockfile.js +168 -0
- package/dist/backends/windows/paths.d.ts +2 -0
- package/dist/backends/windows/paths.js +17 -0
- package/dist/backends/windows/powershell.d.ts +6 -0
- package/dist/backends/windows/powershell.js +51 -0
- package/dist/backends/windows/wsl-setup-runtime.d.ts +32 -0
- package/dist/backends/windows/wsl-setup-runtime.js +387 -0
- package/dist/backends/windows/wsl-setup.d.ts +12 -0
- package/dist/backends/windows/wsl-setup.js +108 -0
- package/dist/backends/windows/wsl.d.ts +9 -0
- package/dist/backends/windows/wsl.js +194 -0
- package/dist/cli/commands/apply.d.ts +7 -1
- package/dist/cli/commands/apply.js +39 -15
- package/dist/cli/commands/check.js +3 -0
- package/dist/cli/commands/init.js +2 -0
- package/dist/cli/commands/install.d.ts +7 -0
- package/dist/cli/commands/install.js +41 -0
- package/dist/cli/commands/switch.d.ts +6 -0
- package/dist/cli/commands/switch.js +53 -13
- package/dist/cli/commands/update.d.ts +6 -1
- package/dist/cli/commands/update.js +41 -10
- package/dist/cli/index.js +65 -3
- package/dist/cli/windows-state.d.ts +56 -0
- package/dist/cli/windows-state.js +341 -0
- package/dist/helpers/index.d.ts +1 -1
- package/dist/helpers/utils.d.ts +1 -0
- package/dist/helpers/utils.js +8 -0
- package/dist/helpers/windows.d.ts +53 -7
- package/dist/helpers/windows.js +351 -28
- package/dist/index.d.ts +4 -2
- package/dist/skill.d.ts +2 -0
- package/dist/skill.js +503 -0
- package/dist/types/windows.d.ts +82 -1
- package/package.json +3 -1
- package/scripts/bootstrap-nixos.sh +51 -0
- package/scripts/bootstrap-windows.ps1 +216 -0
package/dist/cli/index.js
CHANGED
|
@@ -4,47 +4,66 @@ import { parseArgs } from "node:util";
|
|
|
4
4
|
import { apply } from "./commands/apply.js";
|
|
5
5
|
import { check } from "./commands/check.js";
|
|
6
6
|
import { init } from "./commands/init.js";
|
|
7
|
+
import { installSkill } from "./commands/install.js";
|
|
7
8
|
import { inspect } from "./commands/inspect.js";
|
|
8
9
|
import { switchCommand } from "./commands/switch.js";
|
|
9
10
|
import { update } from "./commands/update.js";
|
|
11
|
+
import { renderSkill } from "../skill.js";
|
|
12
|
+
import { forgetWindowsResource, windowsStatePath } from "./windows-state.js";
|
|
10
13
|
const { positionals, values } = parseArgs({
|
|
11
14
|
allowPositionals: true,
|
|
12
15
|
options: {
|
|
13
16
|
host: { type: "string" },
|
|
14
17
|
dry: { type: "boolean", default: false },
|
|
18
|
+
yes: { type: "boolean", short: "y", default: false },
|
|
15
19
|
diff: { type: "boolean", default: false },
|
|
16
20
|
windows: { type: "boolean", default: false },
|
|
17
21
|
strict: { type: "boolean", default: false },
|
|
18
22
|
force: { type: "boolean", default: false },
|
|
23
|
+
skill: { type: "boolean", default: false },
|
|
19
24
|
"escape-report": { type: "boolean", default: false },
|
|
20
25
|
help: { type: "boolean", short: "h", default: false },
|
|
21
26
|
},
|
|
22
27
|
});
|
|
23
28
|
const command = positionals[0];
|
|
29
|
+
if (values.skill) {
|
|
30
|
+
if (command) {
|
|
31
|
+
console.error("The --skill option does not accept a command.");
|
|
32
|
+
process.exit(2);
|
|
33
|
+
}
|
|
34
|
+
process.stdout.write(renderSkill());
|
|
35
|
+
process.exit(0);
|
|
36
|
+
}
|
|
24
37
|
if (values.help || !command) {
|
|
25
38
|
console.log(`
|
|
26
39
|
winix - TypeScript-first system configuration
|
|
27
40
|
|
|
28
41
|
Commands:
|
|
29
42
|
init Scaffold a Winix project
|
|
43
|
+
install skill Install the agent skill wrapper
|
|
30
44
|
apply Generate backend output in .winix/out/
|
|
31
45
|
check Validate configuration
|
|
32
46
|
switch Generate output and run the host activation command
|
|
33
47
|
update Update generated flake.lock and copy it to project root
|
|
34
48
|
inspect Print host composition and fragment graph
|
|
49
|
+
state forget Release Windows removal ownership without deleting a resource
|
|
35
50
|
|
|
36
51
|
Options:
|
|
37
52
|
--host <name> Target a specific host
|
|
38
|
-
--dry
|
|
53
|
+
--dry Preview generation (apply) or activation and managed cleanup (switch)
|
|
54
|
+
-y, --yes Confirm managed Windows removals without prompting (switch)
|
|
39
55
|
--diff Show diff against current output (apply)
|
|
40
|
-
--windows Resolve Windows package lockfile (update)
|
|
56
|
+
--windows Resolve Windows package/module/WSL image lockfile (update)
|
|
41
57
|
--strict Treat conflicts as errors (check)
|
|
42
58
|
--escape-report Show escape hatch usage (check)
|
|
43
|
-
--force Overwrite files (init)
|
|
59
|
+
--force Overwrite files (init, install skill)
|
|
60
|
+
--skill Print version-matched agent instructions
|
|
44
61
|
-h, --help Show this help
|
|
45
62
|
|
|
46
63
|
Examples:
|
|
47
64
|
winix init
|
|
65
|
+
winix install skill
|
|
66
|
+
winix --skill
|
|
48
67
|
winix apply
|
|
49
68
|
winix apply --dry
|
|
50
69
|
winix apply --host wsl-work
|
|
@@ -56,6 +75,10 @@ Examples:
|
|
|
56
75
|
process.exit(0);
|
|
57
76
|
}
|
|
58
77
|
const cwd = process.cwd();
|
|
78
|
+
if (values.yes && command !== "switch") {
|
|
79
|
+
console.error("--yes is only supported by winix switch.");
|
|
80
|
+
process.exit(2);
|
|
81
|
+
}
|
|
59
82
|
switch (command) {
|
|
60
83
|
case "init":
|
|
61
84
|
try {
|
|
@@ -66,6 +89,22 @@ switch (command) {
|
|
|
66
89
|
process.exit(1);
|
|
67
90
|
}
|
|
68
91
|
break;
|
|
92
|
+
case "install":
|
|
93
|
+
if (positionals[1] !== "skill" || positionals.length !== 2) {
|
|
94
|
+
console.error("Usage: winix install skill [--force]");
|
|
95
|
+
process.exit(2);
|
|
96
|
+
}
|
|
97
|
+
try {
|
|
98
|
+
const result = await installSkill(cwd, { force: values.force });
|
|
99
|
+
console.log(result === "current"
|
|
100
|
+
? "✓ Winix skill wrapper is already current"
|
|
101
|
+
: "✓ Installed Winix skill wrapper");
|
|
102
|
+
}
|
|
103
|
+
catch (err) {
|
|
104
|
+
console.error(`\u2717 Error: ${err.message}`);
|
|
105
|
+
process.exit(1);
|
|
106
|
+
}
|
|
107
|
+
break;
|
|
69
108
|
case "apply":
|
|
70
109
|
try {
|
|
71
110
|
await apply(cwd, {
|
|
@@ -90,6 +129,7 @@ switch (command) {
|
|
|
90
129
|
await switchCommand(cwd, {
|
|
91
130
|
host: values.host,
|
|
92
131
|
dry: values.dry,
|
|
132
|
+
yes: values.yes,
|
|
93
133
|
});
|
|
94
134
|
}
|
|
95
135
|
catch (err) {
|
|
@@ -119,6 +159,28 @@ switch (command) {
|
|
|
119
159
|
process.exit(1);
|
|
120
160
|
}
|
|
121
161
|
break;
|
|
162
|
+
case "state":
|
|
163
|
+
try {
|
|
164
|
+
if (process.platform !== "win32")
|
|
165
|
+
throw new Error("Windows applied state is only available on native Windows.");
|
|
166
|
+
let resource;
|
|
167
|
+
if (positionals[1] === "forget" && positionals[2] === "startup" && positionals.length === 4) {
|
|
168
|
+
resource = { kind: "startup", name: positionals[3] };
|
|
169
|
+
}
|
|
170
|
+
else if (positionals[1] === "forget" && positionals[2] === "package" &&
|
|
171
|
+
positionals.length === 5 && ["winget", "msstore"].includes(positionals[3])) {
|
|
172
|
+
resource = { kind: "package", source: positionals[3], id: positionals[4] };
|
|
173
|
+
}
|
|
174
|
+
else {
|
|
175
|
+
throw new Error("Usage: winix state forget startup <name> [--dry] OR winix state forget package <winget|msstore> <id> [--dry]");
|
|
176
|
+
}
|
|
177
|
+
await forgetWindowsResource(windowsStatePath(), resource, values.dry);
|
|
178
|
+
}
|
|
179
|
+
catch (err) {
|
|
180
|
+
console.error(`\u2717 Error: ${err.message}`);
|
|
181
|
+
process.exit(1);
|
|
182
|
+
}
|
|
183
|
+
break;
|
|
122
184
|
default:
|
|
123
185
|
console.error(`Unknown command: ${command}`);
|
|
124
186
|
process.exit(2);
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import type { EvaluatedHost } from "../evaluator/index.js";
|
|
2
|
+
export type ManagedResource = {
|
|
3
|
+
kind: "startup";
|
|
4
|
+
name: string;
|
|
5
|
+
} | {
|
|
6
|
+
kind: "package";
|
|
7
|
+
id: string;
|
|
8
|
+
source: string;
|
|
9
|
+
};
|
|
10
|
+
export type ResourceSnapshot = {
|
|
11
|
+
fingerprint: string;
|
|
12
|
+
} | {
|
|
13
|
+
version: string;
|
|
14
|
+
} | null;
|
|
15
|
+
interface Entry {
|
|
16
|
+
resource: ManagedResource;
|
|
17
|
+
owners: string[];
|
|
18
|
+
owned: boolean;
|
|
19
|
+
snapshot: ResourceSnapshot;
|
|
20
|
+
definition: string;
|
|
21
|
+
}
|
|
22
|
+
interface AppliedState {
|
|
23
|
+
version: 1;
|
|
24
|
+
entries: Record<string, Entry>;
|
|
25
|
+
}
|
|
26
|
+
export interface WindowsStateAdapter {
|
|
27
|
+
inspect(resource: ManagedResource): Promise<ResourceSnapshot>;
|
|
28
|
+
remove(resource: ManagedResource, snapshot: NonNullable<ResourceSnapshot>): Promise<void>;
|
|
29
|
+
}
|
|
30
|
+
export interface ReconcileOptions {
|
|
31
|
+
statePath: string;
|
|
32
|
+
owner: string;
|
|
33
|
+
desired: ManagedResource[];
|
|
34
|
+
definitions: Record<string, string>;
|
|
35
|
+
dry: boolean;
|
|
36
|
+
yes?: boolean;
|
|
37
|
+
adapter: WindowsStateAdapter;
|
|
38
|
+
activate(): Promise<void>;
|
|
39
|
+
report?(message: string): void;
|
|
40
|
+
/** CLI switch holds this lock across backend generation as well as activation. */
|
|
41
|
+
lockHeld?: boolean;
|
|
42
|
+
}
|
|
43
|
+
export declare function resourceKey(resource: ManagedResource): string;
|
|
44
|
+
export declare function managedWindowsResources(host: EvaluatedHost): ManagedResource[];
|
|
45
|
+
export declare function parseAppliedState(text: string): AppliedState;
|
|
46
|
+
export declare function withWindowsStateLock<T>(path: string, dry: boolean, action: () => Promise<T>): Promise<T>;
|
|
47
|
+
export declare function forgetWindowsResource(path: string, resource: ManagedResource, dry: boolean): Promise<void>;
|
|
48
|
+
export declare function confirmWindowsRemovals(yes?: boolean): Promise<void>;
|
|
49
|
+
/**
|
|
50
|
+
* One user/machine inventory, serialized across workspaces. Ownership is granted
|
|
51
|
+
* only after successful activation and never inferred from version locks.
|
|
52
|
+
*/
|
|
53
|
+
export declare function reconcileWindows(opts: ReconcileOptions): Promise<void>;
|
|
54
|
+
export declare const nativeWindowsStateAdapter: WindowsStateAdapter;
|
|
55
|
+
export declare function windowsStatePath(): string;
|
|
56
|
+
export {};
|
|
@@ -0,0 +1,341 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { execFileSync } from "node:child_process";
|
|
3
|
+
import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
|
|
4
|
+
import { hostname } from "node:os";
|
|
5
|
+
import { dirname, join } from "node:path";
|
|
6
|
+
import { createInterface } from "node:readline/promises";
|
|
7
|
+
import { powerShellLiteral } from "../helpers/utils.js";
|
|
8
|
+
import { runCommand } from "./run.js";
|
|
9
|
+
export function resourceKey(resource) {
|
|
10
|
+
return JSON.stringify(resource.kind === "startup"
|
|
11
|
+
? ["startup", resource.name.toLowerCase()]
|
|
12
|
+
: ["package", resource.source.toLowerCase(), resource.id.toLowerCase()]);
|
|
13
|
+
}
|
|
14
|
+
export function managedWindowsResources(host) {
|
|
15
|
+
const windows = host.windows;
|
|
16
|
+
const resources = Object.values(windows.packages ?? {}).map((pkg) => ({ kind: "package", id: pkg.id, source: pkg.source }));
|
|
17
|
+
for (const resource of windows.dsc ?? []) {
|
|
18
|
+
if (resource.winix?.kind === "startup") {
|
|
19
|
+
resources.push({ kind: "startup", name: resource.winix.name });
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
const keys = new Set();
|
|
23
|
+
for (const resource of resources) {
|
|
24
|
+
const key = resourceKey(resource);
|
|
25
|
+
if (keys.has(key))
|
|
26
|
+
throw new Error(`Duplicate managed Windows resource: ${key}`);
|
|
27
|
+
keys.add(key);
|
|
28
|
+
}
|
|
29
|
+
return resources;
|
|
30
|
+
}
|
|
31
|
+
function sameSnapshot(a, b) {
|
|
32
|
+
return JSON.stringify(a) === JSON.stringify(b);
|
|
33
|
+
}
|
|
34
|
+
function validResource(value) {
|
|
35
|
+
if (!value || typeof value !== "object")
|
|
36
|
+
return false;
|
|
37
|
+
if ("kind" in value && value.kind === "startup") {
|
|
38
|
+
return "name" in value && typeof value.name === "string" && value.name.length > 0 &&
|
|
39
|
+
!/[<>:"/\\|?*\x00-\x1f]|[. ]$/.test(value.name) &&
|
|
40
|
+
!/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(value.name);
|
|
41
|
+
}
|
|
42
|
+
return "kind" in value && value.kind === "package" &&
|
|
43
|
+
"id" in value && typeof value.id === "string" && value.id.length > 0 &&
|
|
44
|
+
"source" in value && (value.source === "winget" || value.source === "msstore");
|
|
45
|
+
}
|
|
46
|
+
export function parseAppliedState(text) {
|
|
47
|
+
const value = JSON.parse(text);
|
|
48
|
+
if (!value || typeof value !== "object" || !("version" in value) || value.version !== 1 ||
|
|
49
|
+
!("entries" in value) || !value.entries || typeof value.entries !== "object" || Array.isArray(value.entries)) {
|
|
50
|
+
throw new Error("Invalid Windows applied-state inventory; refusing reconciliation");
|
|
51
|
+
}
|
|
52
|
+
for (const [key, entry] of Object.entries(value.entries)) {
|
|
53
|
+
if (!entry || typeof entry !== "object" || !validResource(entry.resource) ||
|
|
54
|
+
key !== resourceKey(entry.resource) || typeof entry.owned !== "boolean" ||
|
|
55
|
+
typeof entry.definition !== "string" ||
|
|
56
|
+
!Array.isArray(entry.owners) || !entry.owners.every((owner) => typeof owner === "string") ||
|
|
57
|
+
!(entry.snapshot === null || (entry.resource.kind === "startup"
|
|
58
|
+
? typeof entry.snapshot?.fingerprint === "string" && /^[a-f0-9]{64}$/.test(entry.snapshot.fingerprint)
|
|
59
|
+
: typeof entry.snapshot?.version === "string" && entry.snapshot.version.length > 0))) {
|
|
60
|
+
throw new Error(`Invalid Windows applied-state entry: ${key}; refusing reconciliation`);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
return value;
|
|
64
|
+
}
|
|
65
|
+
async function loadState(path) {
|
|
66
|
+
try {
|
|
67
|
+
return parseAppliedState(await readFile(path, "utf8"));
|
|
68
|
+
}
|
|
69
|
+
catch (error) {
|
|
70
|
+
if (error instanceof Error && "code" in error && error.code === "ENOENT") {
|
|
71
|
+
return { version: 1, entries: {} };
|
|
72
|
+
}
|
|
73
|
+
throw error;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
async function saveState(path, state) {
|
|
77
|
+
const temporary = `${path}.tmp`;
|
|
78
|
+
await writeFile(temporary, JSON.stringify(state, null, 2) + "\n", { flag: "wx" });
|
|
79
|
+
try {
|
|
80
|
+
await rename(temporary, path);
|
|
81
|
+
}
|
|
82
|
+
finally {
|
|
83
|
+
await rm(temporary, { force: true });
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
export async function withWindowsStateLock(path, dry, action) {
|
|
87
|
+
const lockPath = `${path}.lock`;
|
|
88
|
+
if (!dry) {
|
|
89
|
+
await mkdir(dirname(path), { recursive: true });
|
|
90
|
+
try {
|
|
91
|
+
await mkdir(lockPath);
|
|
92
|
+
}
|
|
93
|
+
catch (error) {
|
|
94
|
+
throw new Error(`Cannot lock Windows applied state at ${lockPath}. Another activation may be running; ` +
|
|
95
|
+
"after an interrupted activation, inspect the inventory before manually removing the stale lock.", { cause: error });
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
try {
|
|
99
|
+
return await action();
|
|
100
|
+
}
|
|
101
|
+
finally {
|
|
102
|
+
if (!dry)
|
|
103
|
+
await rm(lockPath, { recursive: true });
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
export async function forgetWindowsResource(path, resource, dry) {
|
|
107
|
+
if (!validResource(resource))
|
|
108
|
+
throw new Error("Invalid resource identity");
|
|
109
|
+
await withWindowsStateLock(path, dry, async () => {
|
|
110
|
+
const state = await loadState(path);
|
|
111
|
+
const key = resourceKey(resource);
|
|
112
|
+
const entry = state.entries[key];
|
|
113
|
+
if (!entry)
|
|
114
|
+
throw new Error(`No recorded resource: ${key}`);
|
|
115
|
+
if (!dry) {
|
|
116
|
+
// Keep other owners' requirements; release deletion rights only.
|
|
117
|
+
entry.owned = false;
|
|
118
|
+
await saveState(path, state);
|
|
119
|
+
}
|
|
120
|
+
console.log(`${dry ? "Would release" : "Released"} Winix removal ownership: ${key}. No resource was deleted.`);
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
export async function confirmWindowsRemovals(yes = false) {
|
|
124
|
+
if (yes)
|
|
125
|
+
return;
|
|
126
|
+
if (!process.stdin.isTTY || !process.stdout.isTTY) {
|
|
127
|
+
throw new Error("Switch requires removal confirmation. Preview with switch --dry, then use --yes for noninteractive execution.");
|
|
128
|
+
}
|
|
129
|
+
const prompt = createInterface({ input: process.stdin, output: process.stdout });
|
|
130
|
+
const controller = new AbortController();
|
|
131
|
+
prompt.once("close", () => controller.abort());
|
|
132
|
+
prompt.once("SIGINT", () => controller.abort());
|
|
133
|
+
try {
|
|
134
|
+
const answer = await prompt.question("Continue with switch? [y/N] ", { signal: controller.signal });
|
|
135
|
+
if (!/^(y|yes)$/i.test(answer.trim())) {
|
|
136
|
+
throw new Error("Switch cancelled. No activation or removal was performed.");
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
catch (error) {
|
|
140
|
+
if (controller.signal.aborted) {
|
|
141
|
+
throw new Error("Switch cancelled. No activation or removal was performed.", { cause: error });
|
|
142
|
+
}
|
|
143
|
+
throw error;
|
|
144
|
+
}
|
|
145
|
+
finally {
|
|
146
|
+
prompt.close();
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
/**
|
|
150
|
+
* One user/machine inventory, serialized across workspaces. Ownership is granted
|
|
151
|
+
* only after successful activation and never inferred from version locks.
|
|
152
|
+
*/
|
|
153
|
+
export async function reconcileWindows(opts) {
|
|
154
|
+
const report = opts.report ?? console.log;
|
|
155
|
+
const desired = new Map(opts.desired.map((resource) => [resourceKey(resource), resource]));
|
|
156
|
+
if (desired.size !== opts.desired.length)
|
|
157
|
+
throw new Error("Duplicate managed Windows resources");
|
|
158
|
+
const reconcile = async () => {
|
|
159
|
+
const state = await loadState(opts.statePath);
|
|
160
|
+
const before = new Map();
|
|
161
|
+
for (const [key, resource] of desired) {
|
|
162
|
+
const current = await opts.adapter.inspect(resource);
|
|
163
|
+
before.set(key, current);
|
|
164
|
+
const entry = state.entries[key];
|
|
165
|
+
if (typeof opts.definitions[key] !== "string")
|
|
166
|
+
throw new Error(`Missing resource definition: ${key}`);
|
|
167
|
+
if (entry?.owners.some((owner) => owner !== opts.owner) && entry.definition !== opts.definitions[key]) {
|
|
168
|
+
throw new Error(`Conflicting declaration for resource required by another workspace/host: ${key}`);
|
|
169
|
+
}
|
|
170
|
+
if (entry?.owned && current !== null && !sameSnapshot(current, entry.snapshot)) {
|
|
171
|
+
throw new Error(`Managed resource changed outside Winix: ${key}. Restore it or explicitly resolve ownership before activation.`);
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
const removals = [];
|
|
175
|
+
for (const [key, entry] of Object.entries(state.entries)) {
|
|
176
|
+
if (!entry.owners.includes(opts.owner) && entry.owners.length > 0)
|
|
177
|
+
continue;
|
|
178
|
+
if (desired.has(key))
|
|
179
|
+
continue;
|
|
180
|
+
const others = entry.owners.filter((owner) => owner !== opts.owner);
|
|
181
|
+
if (others.length > 0)
|
|
182
|
+
continue;
|
|
183
|
+
if (!entry.owned) {
|
|
184
|
+
report(`Leaving externally owned resource untouched: ${key}`);
|
|
185
|
+
continue;
|
|
186
|
+
}
|
|
187
|
+
const current = await opts.adapter.inspect(entry.resource);
|
|
188
|
+
if (current !== null && !sameSnapshot(current, entry.snapshot)) {
|
|
189
|
+
throw new Error(`Refusing to remove externally modified resource: ${key}. Resolve ownership explicitly.`);
|
|
190
|
+
}
|
|
191
|
+
report(`${current === null ? "Already absent" : opts.dry ? "Would remove" : "Planned removal"}: ${key}`);
|
|
192
|
+
removals.push([key, entry, current]);
|
|
193
|
+
}
|
|
194
|
+
if (opts.dry) {
|
|
195
|
+
await opts.activate();
|
|
196
|
+
return;
|
|
197
|
+
}
|
|
198
|
+
if (removals.some(([, , current]) => current !== null)) {
|
|
199
|
+
report("Package uninstallers may remove application data.");
|
|
200
|
+
await confirmWindowsRemovals(opts.yes);
|
|
201
|
+
}
|
|
202
|
+
await opts.activate();
|
|
203
|
+
// Capture all desired outcomes before committing any new ownership.
|
|
204
|
+
const after = new Map();
|
|
205
|
+
for (const [key, resource] of desired) {
|
|
206
|
+
const current = await opts.adapter.inspect(resource);
|
|
207
|
+
if (current === null)
|
|
208
|
+
throw new Error(`Activation succeeded but managed resource is missing: ${key}`);
|
|
209
|
+
const entry = state.entries[key];
|
|
210
|
+
if (entry && entry.owners.some((owner) => owner !== opts.owner) && !sameSnapshot(current, entry.snapshot)) {
|
|
211
|
+
throw new Error(`Activation changed a resource required by another workspace/host: ${key}`);
|
|
212
|
+
}
|
|
213
|
+
after.set(key, current);
|
|
214
|
+
}
|
|
215
|
+
for (const entry of Object.values(state.entries)) {
|
|
216
|
+
entry.owners = entry.owners.filter((owner) => owner !== opts.owner);
|
|
217
|
+
}
|
|
218
|
+
for (const [key, resource] of desired) {
|
|
219
|
+
const previous = state.entries[key];
|
|
220
|
+
const initial = before.get(key) ?? null;
|
|
221
|
+
const current = after.get(key);
|
|
222
|
+
state.entries[key] = {
|
|
223
|
+
resource,
|
|
224
|
+
owners: [...(previous?.owners ?? []), opts.owner],
|
|
225
|
+
owned: previous?.owned === true || initial === null ||
|
|
226
|
+
(resource.kind === "startup" && !sameSnapshot(initial, current)),
|
|
227
|
+
snapshot: current,
|
|
228
|
+
definition: opts.definitions[key],
|
|
229
|
+
};
|
|
230
|
+
}
|
|
231
|
+
await saveState(opts.statePath, state);
|
|
232
|
+
for (const [key, entry, observed] of removals) {
|
|
233
|
+
// Recheck immediately before a destructive operation, not just at plan time.
|
|
234
|
+
const current = await opts.adapter.inspect(entry.resource);
|
|
235
|
+
if (!sameSnapshot(current, observed))
|
|
236
|
+
throw new Error(`Resource changed after removal planning: ${key}`);
|
|
237
|
+
if (current !== null) {
|
|
238
|
+
await opts.adapter.remove(entry.resource, current);
|
|
239
|
+
if (await opts.adapter.inspect(entry.resource) !== null)
|
|
240
|
+
throw new Error(`Resource still exists after removal: ${key}`);
|
|
241
|
+
}
|
|
242
|
+
delete state.entries[key];
|
|
243
|
+
await saveState(opts.statePath, state);
|
|
244
|
+
report(`Removed: ${key}`);
|
|
245
|
+
}
|
|
246
|
+
for (const [key, entry] of Object.entries(state.entries)) {
|
|
247
|
+
if (!entry.owned && entry.owners.length === 0)
|
|
248
|
+
delete state.entries[key];
|
|
249
|
+
}
|
|
250
|
+
await saveState(opts.statePath, state);
|
|
251
|
+
};
|
|
252
|
+
if (opts.lockHeld)
|
|
253
|
+
await reconcile();
|
|
254
|
+
else
|
|
255
|
+
await withWindowsStateLock(opts.statePath, opts.dry, reconcile);
|
|
256
|
+
}
|
|
257
|
+
function powershell(script) {
|
|
258
|
+
return execFileSync("pwsh", [
|
|
259
|
+
"-NoLogo", "-NoProfile", "-NonInteractive", "-EncodedCommand",
|
|
260
|
+
Buffer.from("$ErrorActionPreference = 'Stop'\n" + script, "utf16le").toString("base64"),
|
|
261
|
+
], { encoding: "utf8", stdio: ["pipe", "pipe", "pipe"], timeout: 60000 }).trim();
|
|
262
|
+
}
|
|
263
|
+
function startupPathScript(name) {
|
|
264
|
+
return `$root = [Environment]::GetFolderPath('Startup')
|
|
265
|
+
if (-not $root) { throw 'Windows Startup folder is unavailable' }
|
|
266
|
+
$path = Join-Path $root ${powerShellLiteral(name + ".lnk")}`;
|
|
267
|
+
}
|
|
268
|
+
function packageState(resource) {
|
|
269
|
+
const result = JSON.parse(execFileSync("dsc", [
|
|
270
|
+
"resource", "get", "--resource", "Microsoft.WinGet/Package", "--file", "-",
|
|
271
|
+
], {
|
|
272
|
+
encoding: "utf8", input: JSON.stringify({ id: resource.id, source: resource.source }),
|
|
273
|
+
stdio: ["pipe", "pipe", "pipe"], timeout: 60000,
|
|
274
|
+
}));
|
|
275
|
+
if (!result || typeof result !== "object" || !("actualState" in result) ||
|
|
276
|
+
!result.actualState || typeof result.actualState !== "object")
|
|
277
|
+
throw new Error("Invalid package inventory response");
|
|
278
|
+
const state = result.actualState;
|
|
279
|
+
if (!("id" in state) || typeof state.id !== "string" ||
|
|
280
|
+
state.id.toLowerCase() !== resource.id.toLowerCase() ||
|
|
281
|
+
!("source" in state) || typeof state.source !== "string" ||
|
|
282
|
+
state.source.toLowerCase() !== resource.source.toLowerCase()) {
|
|
283
|
+
throw new Error(`Package inventory identity mismatch for ${resource.id}`);
|
|
284
|
+
}
|
|
285
|
+
if ("_exist" in state && state._exist === false)
|
|
286
|
+
return null;
|
|
287
|
+
if (!("_exist" in state) || state._exist !== true || !("version" in state) ||
|
|
288
|
+
typeof state.version !== "string" || !state.version) {
|
|
289
|
+
throw new Error(`Cannot determine installed version of ${resource.id}; refusing ownership tracking`);
|
|
290
|
+
}
|
|
291
|
+
return { version: state.version };
|
|
292
|
+
}
|
|
293
|
+
export const nativeWindowsStateAdapter = {
|
|
294
|
+
async inspect(resource) {
|
|
295
|
+
if (resource.kind === "package")
|
|
296
|
+
return packageState(resource);
|
|
297
|
+
const hash = powershell(`${startupPathScript(resource.name)}
|
|
298
|
+
if (Test-Path -LiteralPath $path) {
|
|
299
|
+
if (-not (Test-Path -LiteralPath $path -PathType Leaf)) { throw "Startup entry is not a file: $path" }
|
|
300
|
+
(Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash.ToLowerInvariant()
|
|
301
|
+
}`);
|
|
302
|
+
if (!hash)
|
|
303
|
+
return null;
|
|
304
|
+
if (!/^[a-f0-9]{64}$/.test(hash))
|
|
305
|
+
throw new Error("Invalid startup fingerprint");
|
|
306
|
+
return { fingerprint: hash };
|
|
307
|
+
},
|
|
308
|
+
async remove(resource, snapshot) {
|
|
309
|
+
if (resource.kind === "package") {
|
|
310
|
+
if (!("version" in snapshot))
|
|
311
|
+
throw new Error("Missing package version for uninstall");
|
|
312
|
+
await runCommand("winget", [
|
|
313
|
+
"uninstall", "--id", resource.id, "--exact", "--source", resource.source,
|
|
314
|
+
"--version", snapshot.version, "--silent", "--disable-interactivity",
|
|
315
|
+
]);
|
|
316
|
+
}
|
|
317
|
+
else {
|
|
318
|
+
if (!("fingerprint" in snapshot))
|
|
319
|
+
throw new Error("Missing shortcut fingerprint for removal");
|
|
320
|
+
powershell(`${startupPathScript(resource.name)}
|
|
321
|
+
if ((Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash.ToLowerInvariant() -cne ${powerShellLiteral(snapshot.fingerprint)}) {
|
|
322
|
+
throw 'Startup entry changed before removal'
|
|
323
|
+
}
|
|
324
|
+
Remove-Item -LiteralPath $path`);
|
|
325
|
+
}
|
|
326
|
+
},
|
|
327
|
+
};
|
|
328
|
+
export function windowsStatePath() {
|
|
329
|
+
const identity = JSON.parse(powershell(`
|
|
330
|
+
@{
|
|
331
|
+
LocalAppData = [Environment]::GetFolderPath('LocalApplicationData')
|
|
332
|
+
Sid = [Security.Principal.WindowsIdentity]::GetCurrent().User.Value
|
|
333
|
+
} | ConvertTo-Json -Compress`));
|
|
334
|
+
if (!identity || typeof identity !== "object" || !("LocalAppData" in identity) ||
|
|
335
|
+
typeof identity.LocalAppData !== "string" || !identity.LocalAppData ||
|
|
336
|
+
!("Sid" in identity) || typeof identity.Sid !== "string" || !/^S-[0-9-]+$/.test(identity.Sid)) {
|
|
337
|
+
throw new Error("Cannot determine Windows user inventory location");
|
|
338
|
+
}
|
|
339
|
+
const scope = createHash("sha256").update(hostname() + "\0" + identity.Sid).digest("hex");
|
|
340
|
+
return join(identity.LocalAppData, "Winix", `applied-${scope}.json`);
|
|
341
|
+
}
|
package/dist/helpers/index.d.ts
CHANGED
|
@@ -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, WinFileEncoding, WinFileNamespace, WinFileOpts, WinPackageArg, WinPackageSpec, WinPathNamespace, WinRawCommandArg, WinRawCommandSpec, WinSettingOpts, } from "./windows.js";
|
|
16
|
+
export type { WindowsHelper, WinDscSpec, WinEnvNamespace, WinEnvOpts, WinEnvScope, WinFileEncoding, WinFileNamespace, WinFileOpts, WinPackageArg, WinPackageSpec, WinPathNamespace, WinRawCommandArg, WinRawCommandSpec, WinSettingOpts, WinPowerShellModuleOpts, WinStartupCommandSpec, WinStartupNamespace, WinOptionalFeatureOpts, WinWslDistroSpec, WinWslOpts, WinWslNamespace, } from "./windows.js";
|
package/dist/helpers/utils.d.ts
CHANGED
package/dist/helpers/utils.js
CHANGED
|
@@ -6,3 +6,11 @@
|
|
|
6
6
|
export function normalizeArgs(args) {
|
|
7
7
|
return Array.isArray(args[0]) ? args[0] : args;
|
|
8
8
|
}
|
|
9
|
+
export function powerShellLiteral(value) {
|
|
10
|
+
if (!/[^\x00-\x7f]/.test(value))
|
|
11
|
+
return `'${value.replaceAll("'", "''")}'`;
|
|
12
|
+
// DSC's pwsh stdin transport can use an OEM code page. Keep script data ASCII.
|
|
13
|
+
const escaped = value.replaceAll("`", "``").replaceAll('"', '`"').replaceAll("$", "`$")
|
|
14
|
+
.replace(/[^\x00-\x7f]/gu, (character) => "`u{" + character.codePointAt(0).toString(16) + "}");
|
|
15
|
+
return `"${escaped}"`;
|
|
16
|
+
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { ResourceHandle } from "../core/types.js";
|
|
2
|
-
import type { WinDscProperties, WinPackageSource, WinSettings } from "../types/index.js";
|
|
2
|
+
import type { WinDscProperties, WinDscResource, WinPackageSource, WinSettings, WinFilePath, WinKnownFolder, WinKnownFolderName, WinStartupCommand, WinWslConfig, WinWslDistro, WinWslSetup } from "../types/index.js";
|
|
3
3
|
/**
|
|
4
4
|
* Accepted call shapes for `windows.package(...)`.
|
|
5
5
|
*
|
|
@@ -47,6 +47,35 @@ export interface WinDscSpec {
|
|
|
47
47
|
export interface WinSettingOpts {
|
|
48
48
|
dependsOn?: ResourceHandle | ResourceHandle[];
|
|
49
49
|
}
|
|
50
|
+
export interface WinPowerShellModuleOpts {
|
|
51
|
+
/** Registered PowerShell repository on the target. Defaults to PSGallery. */
|
|
52
|
+
repository?: string;
|
|
53
|
+
dependsOn?: ResourceHandle | ResourceHandle[];
|
|
54
|
+
}
|
|
55
|
+
export interface WinStartupCommandSpec extends WinStartupCommand {
|
|
56
|
+
backup?: boolean;
|
|
57
|
+
force?: boolean;
|
|
58
|
+
dependsOn?: ResourceHandle | ResourceHandle[];
|
|
59
|
+
}
|
|
60
|
+
export interface WinStartupNamespace {
|
|
61
|
+
command(name: string, spec: WinStartupCommandSpec): ResourceHandle;
|
|
62
|
+
}
|
|
63
|
+
export interface WinOptionalFeatureOpts {
|
|
64
|
+
enabled?: boolean;
|
|
65
|
+
dependsOn?: ResourceHandle | ResourceHandle[];
|
|
66
|
+
}
|
|
67
|
+
export interface WinWslDistroSpec extends Omit<WinWslDistro, "name" | "default"> {
|
|
68
|
+
default?: boolean;
|
|
69
|
+
dependsOn?: ResourceHandle | ResourceHandle[];
|
|
70
|
+
}
|
|
71
|
+
export interface WinWslOpts extends Pick<WinFileOpts, "backup" | "force" | "dependsOn"> {
|
|
72
|
+
config?: WinWslConfig;
|
|
73
|
+
}
|
|
74
|
+
export interface WinWslNamespace {
|
|
75
|
+
(opts?: WinWslOpts): ResourceHandle;
|
|
76
|
+
distro(name: string, spec: WinWslDistroSpec): ResourceHandle;
|
|
77
|
+
}
|
|
78
|
+
export declare function filePathExpression(value: WinFilePath): string;
|
|
50
79
|
/** Scope for Windows environment and PATH writes. */
|
|
51
80
|
export type WinEnvScope = "user" | "machine";
|
|
52
81
|
/** Options shared by `windows.env.*` and `windows.path.*` methods. */
|
|
@@ -64,6 +93,9 @@ export interface WinFileOpts {
|
|
|
64
93
|
encoding?: WinFileEncoding;
|
|
65
94
|
dependsOn?: ResourceHandle | ResourceHandle[];
|
|
66
95
|
}
|
|
96
|
+
/** Rebuild scripts after the emitter supplies the config directory. */
|
|
97
|
+
export declare function resolveWindowsFileProperties(resource: WinDscResource, configDir?: string, sourcePath?: (path: string) => string): WinDscProperties | undefined;
|
|
98
|
+
export declare function filePathPrelude(): string[];
|
|
67
99
|
export interface WinEnvNamespace {
|
|
68
100
|
set(name: string, value: string, opts?: WinEnvOpts): ResourceHandle;
|
|
69
101
|
remove(name: string, opts?: WinEnvOpts): ResourceHandle;
|
|
@@ -73,12 +105,24 @@ export interface WinPathNamespace {
|
|
|
73
105
|
remove(value: string, opts?: WinEnvOpts): ResourceHandle;
|
|
74
106
|
}
|
|
75
107
|
export interface WinFileNamespace {
|
|
76
|
-
text(target:
|
|
77
|
-
symlink(target:
|
|
78
|
-
copy(target:
|
|
79
|
-
remove(target:
|
|
108
|
+
text(target: WinFilePath, content: string, opts?: WinFileOpts): ResourceHandle;
|
|
109
|
+
symlink(target: WinFilePath, source: string | URL, opts?: WinFileOpts): ResourceHandle;
|
|
110
|
+
copy(target: WinFilePath, source: string | URL, opts?: WinFileOpts): ResourceHandle;
|
|
111
|
+
remove(target: WinFilePath, opts?: WinFileOpts): ResourceHandle;
|
|
80
112
|
}
|
|
81
113
|
export interface WindowsHelper {
|
|
114
|
+
optionalFeature(name: string, opts?: WinOptionalFeatureOpts): ResourceHandle;
|
|
115
|
+
wsl: WinWslNamespace;
|
|
116
|
+
/** Manage named current-user Startup shortcuts without running the commands during apply. */
|
|
117
|
+
startup: WinStartupNamespace;
|
|
118
|
+
/** Resolve a user folder on the target machine during activation. */
|
|
119
|
+
knownFolder: {
|
|
120
|
+
[Folder in WinKnownFolderName]: (path?: string) => WinKnownFolder;
|
|
121
|
+
};
|
|
122
|
+
powershell: {
|
|
123
|
+
/** Install a current-user PowerShell 7 module using winix-windows.lock. */
|
|
124
|
+
module(name: string, opts?: WinPowerShellModuleOpts): ResourceHandle;
|
|
125
|
+
};
|
|
82
126
|
/**
|
|
83
127
|
* Declare a winget/msstore package.
|
|
84
128
|
*
|
|
@@ -96,6 +140,7 @@ export interface WindowsHelper {
|
|
|
96
140
|
* This is an escape hatch, not a declarative/idempotent helper:
|
|
97
141
|
* `RunCommandOnSet` has no real test phase, so the command runs on every
|
|
98
142
|
* `winget configure` apply. Prefer typed helpers when available.
|
|
143
|
+
* Command strings run in PowerShell 7 (`pwsh`); explicit executables are preserved.
|
|
99
144
|
*
|
|
100
145
|
* ```ts
|
|
101
146
|
* windows.raw("New-Item -ItemType Directory -Force -Path $env:USERPROFILE\\.local\\bin")
|
|
@@ -142,7 +187,7 @@ export interface WindowsHelper {
|
|
|
142
187
|
env: WinEnvNamespace;
|
|
143
188
|
/**
|
|
144
189
|
* Ensure a directory is on the PATH, appending/removing surgically via an
|
|
145
|
-
* idempotent `Microsoft.DSC.Transitional/
|
|
190
|
+
* idempotent `Microsoft.DSC.Transitional/PowerShellScript` resource.
|
|
146
191
|
*
|
|
147
192
|
* ```ts
|
|
148
193
|
* windows.path.add("%USERPROFILE%\\.local\\bin");
|
|
@@ -152,7 +197,7 @@ export interface WindowsHelper {
|
|
|
152
197
|
path: WinPathNamespace;
|
|
153
198
|
/**
|
|
154
199
|
* Manage files, copies, and dotfile symlinks declaratively via an idempotent
|
|
155
|
-
* `Microsoft.DSC.Transitional/
|
|
200
|
+
* `Microsoft.DSC.Transitional/PowerShellScript` resource.
|
|
156
201
|
*
|
|
157
202
|
* ```ts
|
|
158
203
|
* windows.file.text("%USERPROFILE%\\.gitconfig", "[user]\n");
|
|
@@ -164,3 +209,4 @@ export interface WindowsHelper {
|
|
|
164
209
|
file: WinFileNamespace;
|
|
165
210
|
}
|
|
166
211
|
export declare const windows: WindowsHelper;
|
|
212
|
+
export declare function normalizeWslSetup(setup: WinWslSetup): WinWslSetup;
|