@adrifer/winix 0.2.0-preview.3 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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))
@@ -25,12 +25,14 @@
25
25
  //
26
26
  // `winget configure -f configuration.winget` runs this directly; the dscv3
27
27
  // processor is selected by the metadata block.
28
+ import { yamlEntry, yamlScalar } from "./yaml.js";
28
29
  import { emptyWindowsLock, reconcileInlinePins, } from "./lockfile.js";
29
30
  import { isWindowsHost } from "./host.js";
30
31
  export { isWindowsHost } from "./host.js";
31
32
  const DSC_SCHEMA = "https://raw.githubusercontent.com/PowerShell/DSC/main/schemas/2023/08/config/document.json";
32
33
  const WINGET_PACKAGE_TYPE = "Microsoft.WinGet/Package";
33
34
  const RUN_COMMAND_ON_SET_TYPE = "Microsoft.DSC.Transitional/RunCommandOnSet";
35
+ const WINDOWS_SETTINGS_MODULE_COMMAND_NAME = "Ensure Microsoft Windows Settings module";
34
36
  /**
35
37
  * Generate Windows bundles for every Windows host in the evaluated workspace.
36
38
  * Non-Windows hosts are skipped.
@@ -54,7 +56,9 @@ export function generateWindows(evaluatedHosts, lock = emptyWindowsLock()) {
54
56
  */
55
57
  function generateConfiguration(hostName, win, lock) {
56
58
  const packages = sortedPackages(win.packages ?? {});
57
- const commands = win.commands ?? [];
59
+ const prepared = prepareWindowsDscResources(win.commands ?? [], win.dsc ?? []);
60
+ const commands = prepared.commands;
61
+ const dscResources = prepared.dscResources;
58
62
  const lines = [];
59
63
  lines.push(`# yaml-language-server: $schema=${DSC_SCHEMA}`);
60
64
  lines.push(`# Generated by Winix for host "${hostName}". Do not edit.`);
@@ -62,14 +66,14 @@ function generateConfiguration(hostName, win, lock) {
62
66
  lines.push("metadata:");
63
67
  lines.push(" winget:");
64
68
  lines.push(" processor: dscv3");
65
- if (packages.length === 0 && commands.length === 0) {
69
+ if (packages.length === 0 && commands.length === 0 && dscResources.length === 0) {
66
70
  lines.push("resources: []");
67
71
  return lines.join("\n") + "\n";
68
72
  }
69
73
  // Two-pass: first assign every resource a schema-valid, unique name and build
70
74
  // the ref → (type, name) map; then render, resolving each resource's
71
75
  // `dependsOn` against that map.
72
- const naming = assignResourceNames(hostName, packages, commands);
76
+ const naming = assignResourceNames(hostName, packages, commands, dscResources);
73
77
  lines.push("resources:");
74
78
  for (const pkg of packages) {
75
79
  const plan = naming.packages.get(pkg);
@@ -79,8 +83,197 @@ function generateConfiguration(hostName, win, lock) {
79
83
  const plan = naming.commands.get(command);
80
84
  lines.push(...renderRawCommandResource(command, plan, naming));
81
85
  }
86
+ for (const resource of dscResources) {
87
+ const plan = naming.dsc.get(resource);
88
+ lines.push(...renderDscResource(resource, plan, naming));
89
+ }
82
90
  return lines.join("\n") + "\n";
83
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
+ }
84
277
  /**
85
278
  * Convert an arbitrary identifier into a DSC v3 instance name, which the schema
86
279
  * restricts to `^[a-zA-Z0-9 ]+$` (letters, numbers, spaces only). Non-matching
@@ -104,13 +297,15 @@ function sanitizeName(raw) {
104
297
  * - On a name collision, a ` N` suffix is appended to keep names unique, since
105
298
  * DSC requires instance names to be unique within a document.
106
299
  */
107
- function assignResourceNames(hostName, packages, commands) {
300
+ function assignResourceNames(hostName, packages, commands, dscResources) {
108
301
  const used = new Set();
109
302
  const plan = {
110
303
  packages: new Map(),
111
304
  commands: new Map(),
305
+ dsc: new Map(),
112
306
  byPackageId: new Map(),
113
307
  byCommandToken: new Map(),
308
+ byDscToken: new Map(),
114
309
  hostName,
115
310
  };
116
311
  const unique = (base) => {
@@ -142,29 +337,55 @@ function assignResourceNames(hostName, packages, commands) {
142
337
  plan.byCommandToken.set(command.token, rp);
143
338
  }
144
339
  }
340
+ let dscCounter = 0;
341
+ for (const resource of dscResources) {
342
+ dscCounter += 1;
343
+ const base = resource.name
344
+ ? sanitizeName(resource.name)
345
+ : `dsc ${dscCounter}`;
346
+ const name = unique(base);
347
+ const rp = { type: resource.resourceType, name };
348
+ plan.dsc.set(resource, rp);
349
+ if (resource.token) {
350
+ plan.byDscToken.set(resource.token, rp);
351
+ }
352
+ }
145
353
  return plan;
146
354
  }
147
355
  /**
148
- * Resolve a resource's `dependsOn` references into DSC v3 `resourceId()`
149
- * lookup strings. Throws when a referenced resource is not present in this
150
- * host's naming plan, which happens if a handle from another host is passed to
151
- * `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).
152
363
  */
153
364
  function resolveDependsOnRefs(refs, naming) {
154
365
  if (!refs || refs.length === 0)
155
366
  return [];
156
367
  const ids = [];
157
368
  for (const ref of refs) {
158
- const target = ref.kind === "package"
159
- ? naming.byPackageId.get(ref.id)
160
- : naming.byCommandToken.get(ref.token);
369
+ let target;
370
+ let what;
371
+ if (ref.kind === "package") {
372
+ target = naming.byPackageId.get(ref.id);
373
+ what = `package "${ref.id}"`;
374
+ }
375
+ else if (ref.kind === "command") {
376
+ target = naming.byCommandToken.get(ref.token);
377
+ what = "a raw command";
378
+ }
379
+ else {
380
+ target = naming.byDscToken.get(ref.token);
381
+ what = "a DSC resource";
382
+ }
161
383
  if (!target) {
162
- const what = ref.kind === "package" ? `package "${ref.id}"` : "a raw command";
163
384
  throw new Error(`windows dependsOn references ${what} that is not declared in host ` +
164
385
  `"${naming.hostName}". Resources can only depend on other resources ` +
165
386
  `within the same host.`);
166
387
  }
167
- ids.push(`[resourceId('${target.type}', '${target.name}')]`);
388
+ ids.push(target.name);
168
389
  }
169
390
  return ids;
170
391
  }
@@ -228,9 +449,45 @@ function renderRawCommandResource(command, plan, naming) {
228
449
  return out;
229
450
  }
230
451
  /**
231
- * The thin apply entry point. Idempotency, elevation, ordering, and error
232
- * reporting all live inside `winget configure` / the DSC v3 processor.
452
+ * Render one generic DSC resource (from `windows.dsc(...)` and typed helpers)
453
+ * as a DSC v3 resource block. The `properties` object is serialized verbatim
454
+ * via the YAML helper, so arbitrary nested DSC resource shapes round-trip
455
+ * exactly.
233
456
  */
457
+ function renderDscResource(resource, plan, naming) {
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
+ }
463
+ out.push(` - name: ${yamlScalar(plan.name)}`);
464
+ out.push(` type: ${yamlScalar(resource.resourceType)}`);
465
+ const deps = resolveDependsOnRefs(resource.dependsOn, naming);
466
+ if (deps.length > 0) {
467
+ out.push(` dependsOn: ${yamlStringArray(deps)}`);
468
+ }
469
+ const properties = resource.properties ?? {};
470
+ if (Object.keys(properties).length === 0) {
471
+ out.push(` properties: {}`);
472
+ }
473
+ else {
474
+ // Serialize properties at depth 0, then re-indent under `properties:` (2
475
+ // levels deep within the resource block: 4 spaces).
476
+ out.push(` properties:`);
477
+ for (const [key, value] of Object.entries(properties)) {
478
+ const lines = yamlEntry(key, value, 0);
479
+ for (const line of lines) {
480
+ out.push(` ${line}`);
481
+ }
482
+ }
483
+ }
484
+ if (resource.elevated) {
485
+ out.push(` metadata:`);
486
+ out.push(` winget:`);
487
+ out.push(` securityContext: elevated`);
488
+ }
489
+ return out;
490
+ }
234
491
  function generateApplyScript() {
235
492
  return [
236
493
  "# Generated by Winix. Do not edit.",
@@ -267,17 +524,21 @@ function lockedVersionForPackage(pkg, lock) {
267
524
  return entry.version;
268
525
  }
269
526
  /**
270
- * Render a YAML scalar. Package ids and sources are simple tokens; quote
271
- * defensively only if the value contains YAML-significant characters.
527
+ * Render a quoted YAML string for `dependsOn` array items, which are always
528
+ * quoted because they contain `[`, `]`, `'`, and `(` (the `resourceId(...)`
529
+ * expression). Reuses the shared scalar quoting via a forced-quote path.
272
530
  */
273
- function yamlScalar(value) {
274
- if (/^[A-Za-z0-9._+\-]+$/.test(value))
275
- return value;
276
- return yamlQuoted(value);
277
- }
278
531
  function yamlQuoted(value) {
279
- return `"${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
532
+ // The shared yamlScalar would quote these anyway (they contain `[`), but be
533
+ // explicit: dependsOn ids are always emitted quoted.
534
+ const escaped = value
535
+ .replace(/\\/g, "\\\\")
536
+ .replace(/"/g, '\\"');
537
+ return `"${escaped}"`;
280
538
  }
281
539
  function yamlStringArray(values) {
282
540
  return `[${values.map((value) => yamlQuoted(value)).join(", ")}]`;
283
541
  }
542
+ function psSingleQuoted(value) {
543
+ return `'${value.replace(/'/g, "''")}'`;
544
+ }
@@ -0,0 +1,27 @@
1
+ /** A JSON-like value the serializer accepts. */
2
+ export type YamlValue = string | number | boolean | null | YamlValue[] | {
3
+ [key: string]: YamlValue;
4
+ };
5
+ /**
6
+ * Serialize a value as block-style YAML lines at the given indent depth.
7
+ * Returns an array of lines WITHOUT a trailing newline; the caller joins them.
8
+ *
9
+ * The `keyContext` form (rendering a value that sits to the right of a `key:`)
10
+ * is handled by the caller via {@link yamlEntry}; this function renders a value
11
+ * standing on its own (e.g. an array item or the document root).
12
+ */
13
+ export declare function yamlLines(value: YamlValue, depth?: number): string[];
14
+ /**
15
+ * Render a single `key: value` entry, choosing inline vs. block layout based on
16
+ * the value's shape:
17
+ * - scalars render inline: `key: value`
18
+ * - empty collections render inline: `key: []` / `key: {}`
19
+ * - non-empty arrays/objects render on following indented lines
20
+ */
21
+ export declare function yamlEntry(key: string, value: YamlValue, depth: number): string[];
22
+ /**
23
+ * Render a scalar (string | number | boolean | null). Strings are quoted unless
24
+ * they are safe plain tokens, so values like `Present`, `winget`, or `Git.Git`
25
+ * stay unquoted while paths, spaces, and YAML-significant characters are quoted.
26
+ */
27
+ export declare function yamlScalar(value: string | number | boolean | null): string;
@@ -0,0 +1,185 @@
1
+ // Minimal YAML value serializer for the Windows DSC emitter.
2
+ //
3
+ // Winix emits Nix by hand and has zero runtime dependencies; the Windows
4
+ // backend keeps that property by serializing the small, well-typed subset of
5
+ // YAML that DSC v3 configuration documents need, rather than pulling in a YAML
6
+ // library.
7
+ //
8
+ // SCOPE: this serializes arbitrary *JSON-like* values (string, number, boolean,
9
+ // null, arrays, plain objects) into block-style YAML. It is used for the
10
+ // `properties` of generic and typed DSC resources. It is deliberately NOT a
11
+ // general YAML emitter: it does not handle anchors, tags, or non-JSON values.
12
+ //
13
+ // DETERMINISM: object keys are emitted in insertion order. Callers that need a
14
+ // stable document order across runs must build their objects deterministically
15
+ // (the helpers do: they construct property objects in a fixed field order).
16
+ const INDENT = " ";
17
+ /**
18
+ * Serialize a value as block-style YAML lines at the given indent depth.
19
+ * Returns an array of lines WITHOUT a trailing newline; the caller joins them.
20
+ *
21
+ * The `keyContext` form (rendering a value that sits to the right of a `key:`)
22
+ * is handled by the caller via {@link yamlEntry}; this function renders a value
23
+ * standing on its own (e.g. an array item or the document root).
24
+ */
25
+ export function yamlLines(value, depth = 0) {
26
+ const pad = INDENT.repeat(depth);
27
+ if (Array.isArray(value)) {
28
+ if (value.length === 0)
29
+ return [`${pad}[]`];
30
+ const out = [];
31
+ for (const item of value) {
32
+ out.push(...yamlArrayItem(item, depth));
33
+ }
34
+ return out;
35
+ }
36
+ if (isPlainObject(value)) {
37
+ const keys = Object.keys(value);
38
+ if (keys.length === 0)
39
+ return [`${pad}{}`];
40
+ const out = [];
41
+ for (const key of keys) {
42
+ out.push(...yamlEntry(key, value[key], depth));
43
+ }
44
+ return out;
45
+ }
46
+ return [`${pad}${yamlScalar(value)}`];
47
+ }
48
+ /**
49
+ * Render a single `key: value` entry, choosing inline vs. block layout based on
50
+ * the value's shape:
51
+ * - scalars render inline: `key: value`
52
+ * - empty collections render inline: `key: []` / `key: {}`
53
+ * - non-empty arrays/objects render on following indented lines
54
+ */
55
+ export function yamlEntry(key, value, depth) {
56
+ const pad = INDENT.repeat(depth);
57
+ const k = yamlKey(key);
58
+ if (Array.isArray(value)) {
59
+ if (value.length === 0)
60
+ return [`${pad}${k}: []`];
61
+ // Array items sit at the SAME indent as the key (block sequence style),
62
+ // matching how the existing emitter and Microsoft's own DSC docs lay out
63
+ // `resources:` and `dependsOn:`.
64
+ const out = [`${pad}${k}:`];
65
+ for (const item of value) {
66
+ out.push(...yamlArrayItem(item, depth));
67
+ }
68
+ return out;
69
+ }
70
+ if (isPlainObject(value)) {
71
+ const keys = Object.keys(value);
72
+ if (keys.length === 0)
73
+ return [`${pad}${k}: {}`];
74
+ const out = [`${pad}${k}:`];
75
+ for (const childKey of keys) {
76
+ out.push(...yamlEntry(childKey, value[childKey], depth + 1));
77
+ }
78
+ return out;
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
+ }
87
+ return [`${pad}${k}: ${yamlScalar(value)}`];
88
+ }
89
+ /**
90
+ * Render one array item as a `- ...` block sequence entry. Scalars render
91
+ * inline after the dash; objects render with their first key on the dash line
92
+ * and the rest indented under it (canonical block-sequence-of-mappings style).
93
+ */
94
+ function yamlArrayItem(value, depth) {
95
+ const pad = INDENT.repeat(depth);
96
+ if (isPlainObject(value)) {
97
+ const keys = Object.keys(value);
98
+ if (keys.length === 0)
99
+ return [`${pad}- {}`];
100
+ const out = [];
101
+ keys.forEach((key, index) => {
102
+ const entryLines = yamlEntry(key, value[key], depth + 1);
103
+ if (index === 0) {
104
+ // Hoist the first entry onto the dash line: "- key: value" or "- key:".
105
+ out.push(`${pad}- ${entryLines[0].slice((depth + 1) * INDENT.length)}`);
106
+ out.push(...entryLines.slice(1));
107
+ }
108
+ else {
109
+ out.push(...entryLines);
110
+ }
111
+ });
112
+ return out;
113
+ }
114
+ if (Array.isArray(value)) {
115
+ // Nested bare arrays are not expected in DSC documents; render defensively
116
+ // as an indented block under the dash.
117
+ if (value.length === 0)
118
+ return [`${pad}- []`];
119
+ const out = [`${pad}-`];
120
+ for (const item of value) {
121
+ out.push(...yamlArrayItem(item, depth + 1));
122
+ }
123
+ return out;
124
+ }
125
+ return [`${pad}- ${yamlScalar(value)}`];
126
+ }
127
+ /** Render an object key, quoting it only when it is not a safe plain token. */
128
+ function yamlKey(key) {
129
+ return isPlainToken(key) ? key : yamlQuoted(key);
130
+ }
131
+ /**
132
+ * Render a scalar (string | number | boolean | null). Strings are quoted unless
133
+ * they are safe plain tokens, so values like `Present`, `winget`, or `Git.Git`
134
+ * stay unquoted while paths, spaces, and YAML-significant characters are quoted.
135
+ */
136
+ export function yamlScalar(value) {
137
+ if (value === null)
138
+ return "null";
139
+ if (typeof value === "boolean")
140
+ return value ? "true" : "false";
141
+ if (typeof value === "number") {
142
+ if (!Number.isFinite(value)) {
143
+ throw new Error(`Cannot serialize non-finite number to YAML: ${value}`);
144
+ }
145
+ return String(value);
146
+ }
147
+ return isPlainToken(value) ? value : yamlQuoted(value);
148
+ }
149
+ /**
150
+ * A "plain token" is a string safe to emit unquoted in YAML in both key and
151
+ * value position. Conservative on purpose: letters, digits, and the few
152
+ * punctuation marks common in package ids / DSC type names (`.`, `_`, `+`,
153
+ * `-`, `/`). Anything else (spaces, `:`, backslashes, quotes, leading
154
+ * indicators) gets quoted.
155
+ *
156
+ * Strings that look like other YAML types (numbers, booleans, null) are NOT
157
+ * plain tokens, so `"true"`, `"123"`, and `"null"` round-trip as strings.
158
+ */
159
+ function isPlainToken(value) {
160
+ if (value.length === 0)
161
+ return false;
162
+ if (!/^[A-Za-z0-9._+/-]+$/.test(value))
163
+ return false;
164
+ // Disambiguate from non-string YAML scalars.
165
+ if (/^[+-]?(\d+\.?\d*|\.\d+)$/.test(value))
166
+ return false; // numeric-looking
167
+ if (/^(true|false|null|yes|no|on|off|~)$/i.test(value))
168
+ return false; // keyword-looking
169
+ return true;
170
+ }
171
+ function yamlQuoted(value) {
172
+ // Double-quoted YAML scalar with the escapes that matter for our inputs.
173
+ const escaped = value
174
+ .replace(/\\/g, "\\\\")
175
+ .replace(/"/g, '\\"')
176
+ .replace(/\n/g, "\\n")
177
+ .replace(/\t/g, "\\t")
178
+ .replace(/\r/g, "\\r");
179
+ return `"${escaped}"`;
180
+ }
181
+ function isPlainObject(value) {
182
+ return (typeof value === "object" &&
183
+ value !== null &&
184
+ !Array.isArray(value));
185
+ }