Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off
2import * as NodeOS from "node:os";
3import * as NodePath from "node:path";
4import * as NodeChildProcess from "node:child_process";
5import * as NodeFS from "node:fs";
6import * as Data from "effect/Data";
7import * as Effect from "effect/Effect";
8import * as FileSystem from "effect/FileSystem";
9import * as Path from "effect/Path";
10
11import { HostProcessEnvironment, HostProcessPlatform } from "./hostProcess.ts";
12import * as Context from "effect/Context";
13
14const PATH_CAPTURE_START = "__T3CODE_PATH_START__";
15const PATH_CAPTURE_END = "__T3CODE_PATH_END__";
16const SHELL_ENV_NAME_PATTERN = /^[A-Z0-9_]+$/;
17const WINDOWS_PATH_DELIMITER = ";";
18const POSIX_PATH_DELIMITER = ":";
19const WINDOWS_SHELL_CANDIDATES = ["pwsh.exe", "powershell.exe"] as const;
20
21type ExecFileSyncLike = (
22 file: string,
23 args: ReadonlyArray<string>,
24 options: { encoding: "utf8"; timeout: number },
25) => string;
26
27function canExecuteFile(filePath: string): boolean {
28 try {
29 NodeFS.accessSync(filePath, NodeFS.constants.X_OK);
30 return true;
31 } catch {
32 return false;
33 }
34}
35
36export interface CommandAvailabilityOptions {
37 readonly env?: NodeJS.ProcessEnv;
38 readonly extendEnv?: boolean;
39}
40
41export type CommandAvailabilityChecker = (
42 command: string,
43 options?: CommandAvailabilityOptions,
44) => Effect.Effect<boolean, never, FileSystem.FileSystem | Path.Path>;
45
46export class CommandResolutionError extends Data.TaggedError("CommandResolutionError")<{
47 readonly command: string;
48 readonly reason: "not-found";
49}> {}
50
51const WINDOWS_SHELL_META_CHARS = /([()\][%!^"`<>&|;, *?])/g;
52
53/**
54 * Escapes a single argument for `cmd.exe` shell mode (`spawn(..., { shell: true })`
55 * on Windows). Node joins the command and arguments with spaces and hands the
56 * resulting string to `cmd.exe` without any quoting, so every dynamic argument
57 * must be escaped to survive both cmd.exe parsing and the target program's
58 * `CommandLineToArgvW` parsing. Mirrors cross-spawn's argument escaping.
59 */
60function escapeWindowsShellArg(arg: string): string {
61 // Double up backslashes that precede a double quote, then escape the quote
62 // itself so it survives CommandLineToArgvW.
63 let escaped = arg.replace(/(\\*)"/g, '$1$1\\"');
64 // Double up trailing backslashes so the closing quote is not escaped away.
65 escaped = escaped.replace(/(\\*)$/, "$1$1");
66 // Quote the whole argument so embedded whitespace is preserved.
67 escaped = `"${escaped}"`;
68 // Escape cmd.exe metacharacters so cmd passes them through verbatim.
69 return escaped.replace(WINDOWS_SHELL_META_CHARS, "^$1");
70}
71
72/**
73 * Escapes arguments for shell-mode spawns: applies {@link escapeWindowsShellArg}
74 * when the platform is `win32` (where `shell: true` routes through `cmd.exe`)
75 * and returns the arguments untouched everywhere else.
76 */
77function sanitizeShellModeArgsForPlatform(
78 args: ReadonlyArray<string>,
79 platform: NodeJS.Platform,
80): Array<string> {
81 return platform === "win32" ? args.map(escapeWindowsShellArg) : [...args];
82}
83
84export interface ResolvedSpawnCommand {
85 readonly command: string;
86 readonly args: ReadonlyArray<string>;
87 readonly shell: boolean;
88}
89
90export type SpawnExecutableResolver = (
91 command: string,
92 platform: NodeJS.Platform,
93 env: NodeJS.ProcessEnv,
94) => string | undefined;
95
96function resolveSpawnExecutableWithNode(
97 command: string,
98 platform: NodeJS.Platform,
99 env: NodeJS.ProcessEnv,
100): string | undefined {
101 const path = platform === "win32" ? NodePath.win32 : NodePath.posix;
102 const windowsPathExtensions = platform === "win32" ? resolveWindowsPathExtensions(env) : [];
103 const candidates = resolveCommandCandidates(
104 command,
105 platform,
106 windowsPathExtensions,
107 path.extname,
108 );
109 const isExecutable = (candidate: string) => {
110 try {
111 if (!NodeFS.statSync(candidate).isFile()) return false;
112 if (platform === "win32") {
113 return windowsPathExtensions.includes(path.extname(candidate).toUpperCase());
114 }
115 return canExecuteFile(candidate);
116 } catch {
117 return false;
118 }
119 };
120
121 if (command.includes("/") || command.includes("\\")) {
122 return candidates.find(isExecutable);
123 }
124
125 for (const pathEntry of (readEnvPath(env) ?? "").split(pathDelimiterForPlatform(platform))) {
126 const normalizedPathEntry = stripWrappingQuotes(pathEntry.trim());
127 if (normalizedPathEntry.length === 0) continue;
128 for (const candidate of candidates) {
129 const candidatePath = path.join(normalizedPathEntry, candidate);
130 if (isExecutable(candidatePath)) return candidatePath;
131 }
132 }
133 return undefined;
134}
135
136export const SpawnExecutableResolution = Context.Reference<SpawnExecutableResolver>(
137 "@t3tools/shared/shell/SpawnExecutableResolution",
138 {
139 defaultValue: () => resolveSpawnExecutableWithNode,
140 },
141);
142
143export interface WindowsEnvironmentProbeOptions {
144 readonly loadProfile?: boolean;
145}
146
147function trimNonEmpty(value: string | null | undefined): string | undefined {
148 const trimmed = value?.trim();
149 return trimmed && trimmed.length > 0 ? trimmed : undefined;
150}
151
152function readUserLoginShell(): string | undefined {
153 try {
154 return trimNonEmpty(NodeOS.userInfo().shell);
155 } catch {
156 return undefined;
157 }
158}
159
160export function listLoginShellCandidates(
161 platform: NodeJS.Platform,
162 shell: string | undefined,
163 userShell = readUserLoginShell(),
164): ReadonlyArray<string> {
165 const fallbackShell =
166 platform === "darwin" ? "/bin/zsh" : platform === "linux" ? "/bin/bash" : undefined;
167 const seen = new Set<string>();
168 const candidates: string[] = [];
169
170 for (const candidate of [trimNonEmpty(shell), trimNonEmpty(userShell), fallbackShell]) {
171 if (!candidate || seen.has(candidate)) {
172 continue;
173 }
174 seen.add(candidate);
175 candidates.push(candidate);
176 }
177
178 return candidates;
179}
180
181export function extractPathFromShellOutput(output: string): string | null {
182 const startIndex = output.indexOf(PATH_CAPTURE_START);
183 if (startIndex === -1) return null;
184
185 const valueStartIndex = startIndex + PATH_CAPTURE_START.length;
186 const endIndex = output.indexOf(PATH_CAPTURE_END, valueStartIndex);
187 if (endIndex === -1) return null;
188
189 const pathValue = output.slice(valueStartIndex, endIndex).trim();
190 return pathValue.length > 0 ? pathValue : null;
191}
192
193export function readPathFromLoginShell(
194 shell: string,
195 execFile: ExecFileSyncLike = NodeChildProcess.execFileSync,
196): string | undefined {
197 return readEnvironmentFromLoginShell(shell, ["PATH"], execFile).PATH;
198}
199
200export function readPathFromLaunchctl(
201 execFile: ExecFileSyncLike = NodeChildProcess.execFileSync,
202): string | undefined {
203 try {
204 return trimNonEmpty(
205 execFile("/bin/launchctl", ["getenv", "PATH"], {
206 encoding: "utf8",
207 timeout: 2000,
208 }),
209 );
210 } catch {
211 return undefined;
212 }
213}
214
215export function mergePathEntries(
216 preferredPath: string | undefined,
217 inheritedPath: string | undefined,
218 platform: NodeJS.Platform,
219): string | undefined {
220 const delimiter = platform === "win32" ? ";" : ":";
221 const merged: string[] = [];
222 const seen = new Set<string>();
223
224 for (const pathValue of [preferredPath, inheritedPath]) {
225 if (!pathValue) continue;
226 for (const entry of pathValue.split(delimiter)) {
227 const trimmedEntry = entry.trim();
228 if (!trimmedEntry || seen.has(trimmedEntry)) {
229 continue;
230 }
231 seen.add(trimmedEntry);
232 merged.push(trimmedEntry);
233 }
234 }
235
236 return merged.length > 0 ? merged.join(delimiter) : undefined;
237}
238
239function envCaptureStart(name: string): string {
240 return `__T3CODE_ENV_${name}_START__`;
241}
242
243function envCaptureEnd(name: string): string {
244 return `__T3CODE_ENV_${name}_END__`;
245}
246
247function buildEnvironmentCaptureCommand(names: ReadonlyArray<string>): string {
248 return names
249 .map((name) => {
250 if (!SHELL_ENV_NAME_PATTERN.test(name)) {
251 throw new Error(`Unsupported environment variable name: ${name}`);
252 }
253
254 return [
255 `printf '%s\\n' '${envCaptureStart(name)}'`,
256 `printenv ${name} || true`,
257 `printf '%s\\n' '${envCaptureEnd(name)}'`,
258 ].join("; ");
259 })
260 .join("; ");
261}
262
263function buildWindowsEnvironmentCaptureCommand(names: ReadonlyArray<string>): string {
264 return [
265 "$ErrorActionPreference = 'Stop'",
266 ...names.flatMap((name) => {
267 if (!SHELL_ENV_NAME_PATTERN.test(name)) {
268 throw new Error(`Unsupported environment variable name: ${name}`);
269 }
270
271 return [
272 `Write-Output '${envCaptureStart(name)}'`,
273 `$value = [Environment]::GetEnvironmentVariable('${name}')`,
274 "if ($null -ne $value -and $value.Length -gt 0) { Write-Output $value }",
275 `Write-Output '${envCaptureEnd(name)}'`,
276 ];
277 }),
278 ].join("; ");
279}
280
281function extractEnvironmentValue(output: string, name: string): string | undefined {
282 const startMarker = envCaptureStart(name);
283 const endMarker = envCaptureEnd(name);
284 const startIndex = output.indexOf(startMarker);
285 if (startIndex === -1) return undefined;
286
287 const valueStartIndex = startIndex + startMarker.length;
288 const endIndex = output.indexOf(endMarker, valueStartIndex);
289 if (endIndex === -1) return undefined;
290
291 const value = output
292 .slice(valueStartIndex, endIndex)
293 .replace(/^\r?\n/, "")
294 .replace(/\r?\n$/, "");
295
296 return value.length > 0 ? value : undefined;
297}
298
299export type ShellEnvironmentReader = (
300 shell: string,
301 names: ReadonlyArray<string>,
302 execFile?: ExecFileSyncLike,
303) => Partial<Record<string, string>>;
304
305export const readEnvironmentFromLoginShell: ShellEnvironmentReader = (
306 shell,
307 names,
308 execFile = NodeChildProcess.execFileSync,
309) => {
310 if (names.length === 0) {
311 return {};
312 }
313
314 const output = execFile(shell, ["-ilc", buildEnvironmentCaptureCommand(names)], {
315 encoding: "utf8",
316 timeout: 5000,
317 });
318
319 const environment: Partial<Record<string, string>> = {};
320 for (const name of names) {
321 const value = extractEnvironmentValue(output, name);
322 if (value !== undefined) {
323 environment[name] = value;
324 }
325 }
326
327 return environment;
328};
329
330export type WindowsShellEnvironmentReader = (
331 names: ReadonlyArray<string>,
332 options?: WindowsEnvironmentProbeOptions,
333) => Partial<Record<string, string>>;
334
335export const WindowsShellEnvironment = Context.Reference<WindowsShellEnvironmentReader>(
336 "@t3tools/shared/shell/WindowsShellEnvironment",
337 {
338 defaultValue: () => readEnvironmentFromWindowsShell,
339 },
340);
341
342export const CommandAvailability = Context.Reference<CommandAvailabilityChecker>(
343 "@t3tools/shared/shell/CommandAvailability",
344 {
345 defaultValue: () => isCommandAvailable,
346 },
347);
348
349export function readEnvironmentFromWindowsShell(
350 names: ReadonlyArray<string>,
351 execFile?: ExecFileSyncLike,
352): Partial<Record<string, string>>;
353export function readEnvironmentFromWindowsShell(
354 names: ReadonlyArray<string>,
355 options?: WindowsEnvironmentProbeOptions,
356 execFile?: ExecFileSyncLike,
357): Partial<Record<string, string>>;
358export function readEnvironmentFromWindowsShell(
359 names: ReadonlyArray<string>,
360 optionsOrExecFile?: WindowsEnvironmentProbeOptions | ExecFileSyncLike,
361 maybeExecFile?: ExecFileSyncLike,
362): Partial<Record<string, string>> {
363 if (names.length === 0) {
364 return {};
365 }
366
367 const options =
368 typeof optionsOrExecFile === "function"
369 ? ({} satisfies WindowsEnvironmentProbeOptions)
370 : (optionsOrExecFile ?? {});
371 const execFile: ExecFileSyncLike =
372 typeof optionsOrExecFile === "function"
373 ? optionsOrExecFile
374 : (maybeExecFile ?? (NodeChildProcess.execFileSync as ExecFileSyncLike));
375 const command = buildWindowsEnvironmentCaptureCommand(names);
376 const args = [
377 "-NoLogo",
378 ...(options.loadProfile ? ([] as const) : (["-NoProfile"] as const)),
379 "-NonInteractive",
380 "-Command",
381 command,
382 ];
383 for (const shell of WINDOWS_SHELL_CANDIDATES) {
384 try {
385 const output = execFile(shell, args, { encoding: "utf8", timeout: 5000 });
386
387 const environment: Partial<Record<string, string>> = {};
388 for (const name of names) {
389 const value = extractEnvironmentValue(output, name);
390 if (value !== undefined) {
391 environment[name] = value;
392 }
393 }
394 return environment;
395 } catch {
396 continue;
397 }
398 }
399
400 return {};
401}
402
403function stripWrappingQuotes(value: string): string {
404 return value.replace(/^"+|"+$/g, "");
405}
406
407function pathDelimiterForPlatform(platform: NodeJS.Platform): string {
408 return platform === "win32" ? WINDOWS_PATH_DELIMITER : POSIX_PATH_DELIMITER;
409}
410
411function normalizePathEntryForComparison(entry: string, platform: NodeJS.Platform): string {
412 const normalized = stripWrappingQuotes(entry.trim());
413 return platform === "win32" ? normalized.toLowerCase() : normalized;
414}
415
416export function mergePathValues(
417 preferredPath: string | undefined,
418 inheritedPath: string | undefined,
419 platform: NodeJS.Platform,
420): string | undefined {
421 const delimiter = pathDelimiterForPlatform(platform);
422 const merged: string[] = [];
423 const seen = new Set<string>();
424
425 for (const rawValue of [preferredPath, inheritedPath]) {
426 if (!rawValue) continue;
427
428 for (const entry of rawValue.split(delimiter)) {
429 const trimmed = entry.trim();
430 if (trimmed.length === 0) continue;
431
432 const normalized = normalizePathEntryForComparison(trimmed, platform);
433 if (normalized.length === 0 || seen.has(normalized)) continue;
434
435 seen.add(normalized);
436 merged.push(trimmed);
437 }
438 }
439
440 return merged.length > 0 ? merged.join(delimiter) : undefined;
441}
442
443function readEnvPath(env: NodeJS.ProcessEnv): string | undefined {
444 return env.PATH ?? env.Path ?? env.path;
445}
446
447function resolvePathEnvironmentVariable(env: NodeJS.ProcessEnv): string {
448 return readEnvPath(env) ?? "";
449}
450
451function resolveWindowsPathExtensions(env: NodeJS.ProcessEnv): ReadonlyArray<string> {
452 const rawValue = env.PATHEXT;
453 const fallback = [".COM", ".EXE", ".BAT", ".CMD"];
454 if (!rawValue) return fallback;
455
456 const parsed: string[] = [];
457 for (const entry of rawValue.split(";")) {
458 const trimmed = entry.trim();
459 if (trimmed.length === 0) continue;
460 parsed.push(trimmed.startsWith(".") ? trimmed.toUpperCase() : `.${trimmed.toUpperCase()}`);
461 }
462 return parsed.length > 0 ? Array.from(new Set(parsed)) : fallback;
463}
464
465function resolveCommandCandidates(
466 command: string,
467 platform: NodeJS.Platform,
468 windowsPathExtensions: ReadonlyArray<string>,
469 extname: (path: string) => string,
470): ReadonlyArray<string> {
471 if (platform !== "win32") return [command];
472 const extension = extname(command);
473 const normalizedExtension = extension.toUpperCase();
474
475 if (extension.length > 0 && windowsPathExtensions.includes(normalizedExtension)) {
476 const commandWithoutExtension = command.slice(0, -extension.length);
477 return Array.from(
478 new Set([
479 command,
480 `${commandWithoutExtension}${normalizedExtension}`,
481 `${commandWithoutExtension}${normalizedExtension.toLowerCase()}`,
482 ]),
483 );
484 }
485
486 const candidates: string[] = [];
487 for (const candidateExtension of windowsPathExtensions) {
488 candidates.push(`${command}${candidateExtension}`);
489 candidates.push(`${command}${candidateExtension.toLowerCase()}`);
490 }
491 return Array.from(new Set(candidates));
492}
493
494const isExecutableFile = Effect.fn("shell.isExecutableFile")(function* (
495 filePath: string,
496 platform: NodeJS.Platform,
497 windowsPathExtensions: ReadonlyArray<string>,
498): Effect.fn.Return<boolean, never, FileSystem.FileSystem | Path.Path> {
499 const fileSystem = yield* FileSystem.FileSystem;
500 const path = yield* Path.Path;
501 const stat = yield* fileSystem.stat(filePath).pipe(Effect.orElseSucceed(() => null));
502 if (stat === null || stat.type !== "File") return false;
503
504 if (platform === "win32") {
505 const extension = path.extname(filePath);
506 if (extension.length === 0) return false;
507 return windowsPathExtensions.includes(extension.toUpperCase());
508 }
509
510 return canExecuteFile(filePath);
511});
512
513const resolveCommandPathForPlatform = Effect.fn("shell.resolveCommandPathForPlatform")(function* (
514 command: string,
515 options: CommandAvailabilityOptions & { readonly platform: NodeJS.Platform },
516): Effect.fn.Return<string, CommandResolutionError, FileSystem.FileSystem | Path.Path> {
517 const path = yield* Path.Path;
518 const platform = options.platform;
519 const env = options.env ?? process.env;
520 const windowsPathExtensions = platform === "win32" ? resolveWindowsPathExtensions(env) : [];
521 const commandCandidates = resolveCommandCandidates(
522 command,
523 platform,
524 windowsPathExtensions,
525 path.extname,
526 );
527
528 if (command.includes("/") || command.includes("\\")) {
529 for (const candidate of commandCandidates) {
530 if (yield* isExecutableFile(candidate, platform, windowsPathExtensions)) {
531 return candidate;
532 }
533 }
534 return yield* new CommandResolutionError({ command, reason: "not-found" });
535 }
536
537 const pathValue = resolvePathEnvironmentVariable(env);
538 if (pathValue.length === 0) {
539 return yield* new CommandResolutionError({ command, reason: "not-found" });
540 }
541 const pathEntries: string[] = [];
542 for (const entry of pathValue.split(pathDelimiterForPlatform(platform))) {
543 const pathEntry = stripWrappingQuotes(entry.trim());
544 if (pathEntry.length > 0) {
545 pathEntries.push(pathEntry);
546 }
547 }
548
549 for (const pathEntry of pathEntries) {
550 for (const candidate of commandCandidates) {
551 const candidatePath = path.join(pathEntry, candidate);
552 if (yield* isExecutableFile(candidatePath, platform, windowsPathExtensions)) {
553 return candidatePath;
554 }
555 }
556 }
557 return yield* new CommandResolutionError({ command, reason: "not-found" });
558});
559
560export const resolveCommandPath = Effect.fn("shell.resolveCommandPath")(function* (
561 command: string,
562 options: CommandAvailabilityOptions = {},
563) {
564 return yield* resolveCommandPathForPlatform(command, {
565 env: options.env ?? (yield* HostProcessEnvironment),
566 platform: yield* HostProcessPlatform,
567 });
568});
569
570export const resolveSpawnCommand = Effect.fn("shell.resolveSpawnCommand")(function* (
571 command: string,
572 args: ReadonlyArray<string>,
573 options: CommandAvailabilityOptions = {},
574): Effect.fn.Return<ResolvedSpawnCommand> {
575 const platform = yield* HostProcessPlatform;
576 if (platform !== "win32") {
577 return { command, args: [...args], shell: false };
578 }
579
580 const hostEnvironment = yield* HostProcessEnvironment;
581 const env =
582 options.env === undefined
583 ? hostEnvironment
584 : options.extendEnv
585 ? { ...hostEnvironment, ...options.env }
586 : options.env;
587 const resolveExecutable = yield* SpawnExecutableResolution;
588 const resolvedCommand = resolveExecutable(command, platform, env) ?? command;
589 const extension = NodePath.win32.extname(resolvedCommand).toLowerCase();
590 if (extension !== ".cmd" && extension !== ".bat") {
591 return { command: resolvedCommand, args: [...args], shell: false };
592 }
593
594 return {
595 command: escapeWindowsShellArg(resolvedCommand),
596 args: sanitizeShellModeArgsForPlatform(args, platform),
597 shell: true,
598 };
599});
600
601export const isCommandAvailable = Effect.fn("shell.isCommandAvailable")(function* (
602 command: string,
603 options: CommandAvailabilityOptions = {},
604) {
605 return yield* resolveCommandPath(command, options).pipe(
606 Effect.as(true),
607 Effect.catchTag("CommandResolutionError", () => Effect.succeed(false)),
608 );
609});
610
611export function resolveKnownWindowsCliDirs(env: NodeJS.ProcessEnv): ReadonlyArray<string> {
612 const appData = env.APPDATA?.trim();
613 const localAppData = env.LOCALAPPDATA?.trim();
614 const userProfile = env.USERPROFILE?.trim();
615
616 return [
617 ...(appData ? [`${appData}\\npm`] : []),
618 ...(localAppData ? [`${localAppData}\\Programs\\nodejs`, `${localAppData}\\Volta\\bin`] : []),
619 ...(localAppData ? [`${localAppData}\\pnpm`, `${localAppData}\\cursor-agent`] : []),
620 ...(userProfile ? [`${userProfile}\\.bun\\bin`, `${userProfile}\\scoop\\shims`] : []),
621 ];
622}
623
624function readWindowsEnvironmentSafely(
625 readEnvironment: WindowsShellEnvironmentReader,
626 names: ReadonlyArray<string>,
627 options?: WindowsEnvironmentProbeOptions,
628): Partial<Record<string, string>> {
629 try {
630 return readEnvironment(names, options);
631 } catch {
632 return {};
633 }
634}
635
636function mergeWindowsEnv(
637 currentEnv: NodeJS.ProcessEnv,
638 patch: Partial<Record<string, string>>,
639): NodeJS.ProcessEnv {
640 const nextEnv: NodeJS.ProcessEnv = { ...currentEnv };
641 for (const [key, value] of Object.entries(patch)) {
642 if (value !== undefined) {
643 nextEnv[key] = value;
644 }
645 }
646 return nextEnv;
647}
648
649export const resolveWindowsEnvironment = Effect.fn("shell.resolveWindowsEnvironment")(function* (
650 env: NodeJS.ProcessEnv,
651): Effect.fn.Return<Partial<NodeJS.ProcessEnv>, never, FileSystem.FileSystem | Path.Path> {
652 const readEnvironment = yield* WindowsShellEnvironment;
653 const commandAvailable = yield* CommandAvailability;
654 const inheritedPath = readEnvPath(env);
655 const shellPath = readWindowsEnvironmentSafely(readEnvironment, ["PATH"], {
656 loadProfile: false,
657 }).PATH;
658 const mergedPath = mergePathValues(shellPath, inheritedPath, "win32");
659 const knownCliPath = resolveKnownWindowsCliDirs(env).join(WINDOWS_PATH_DELIMITER);
660 const baselinePath = mergePathValues(knownCliPath, mergedPath, "win32");
661 const baselinePatch: Partial<NodeJS.ProcessEnv> = baselinePath ? { PATH: baselinePath } : {};
662 const baselineEnv = mergeWindowsEnv(env, baselinePatch);
663
664 if (yield* commandAvailable("node", { env: baselineEnv })) {
665 return baselinePatch;
666 }
667
668 const profiledEnvironment = readWindowsEnvironmentSafely(
669 readEnvironment,
670 ["PATH", "FNM_DIR", "FNM_MULTISHELL_PATH"],
671 { loadProfile: true },
672 );
673 const profiledPath = mergePathValues(profiledEnvironment.PATH, baselinePath, "win32");
674 const profiledPatch: Partial<NodeJS.ProcessEnv> = {
675 ...(profiledPath ? { PATH: profiledPath } : {}),
676 ...(profiledEnvironment.FNM_DIR ? { FNM_DIR: profiledEnvironment.FNM_DIR } : {}),
677 ...(profiledEnvironment.FNM_MULTISHELL_PATH
678 ? { FNM_MULTISHELL_PATH: profiledEnvironment.FNM_MULTISHELL_PATH }
679 : {}),
680 };
681 return Object.keys(profiledPatch).length > 0
682 ? { ...baselinePatch, ...profiledPatch }
683 : baselinePatch;
684});