Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

externalLauncher.ts

846 lines28.0 KB

1import * as NodePath from "@effect/platform-node/NodePath";
2import {
3 EDITORS,
4 ExternalLauncherError,
5 ExternalLauncherBrowserSpawnError,
6 ExternalLauncherCommandNotFoundError,
7 ExternalLauncherEditorSpawnError,
8 ExternalLauncherUnknownEditorError,
9 ExternalLauncherUnsupportedEditorError,
10 ExternalLauncherUnsupportedTargetError,
11 type EditorId,
12 type FileManagerRevealKind,
13 type LaunchEditorInput,
14} from "@t3tools/contracts";
15import { resolveEditorCommand } from "@t3tools/shared/editor";
16import * as HostProcess from "@t3tools/shared/HostProcess";
17import {
18 isCommandAvailable,
19 resolveSpawnCommand,
20 withPathDirectoryListings,
21} from "@t3tools/shared/shell";
22import * as Config from "effect/Config";
23import * as Context from "effect/Context";
24import * as Effect from "effect/Effect";
25import * as Base64 from "effect/encoding/Base64";
26import * as FileSystem from "effect/FileSystem";
27import * as Layer from "effect/Layer";
28import * as Option from "effect/Option";
29import * as Path from "effect/Path";
30import * as Schema from "effect/Schema";
31import * as Stream from "effect/Stream";
32import * as ChildProcess from "effect/process/ChildProcess";
33import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
34​
35import { makeStaleWhileRevalidate } from "../environment/staleWhileRevalidate.ts";
36export {
37 ExternalLauncherError,
38 ExternalLauncherBrowserSpawnError,
39 ExternalLauncherCommandNotFoundError,
40 ExternalLauncherEditorSpawnError,
41 ExternalLauncherUnknownEditorError,
42 ExternalLauncherUnsupportedEditorError,
43 ExternalLauncherUnsupportedTargetError,
44} from "@t3tools/contracts";
45export type { LaunchEditorInput };
46interface EditorLaunch {
47 readonly editor: EditorId;
48 readonly target: string;
49 readonly command: string;
50 readonly args: ReadonlyArray<string>;
51 readonly detached?: boolean;
53​
54interface ProcessLaunch {
55 readonly command: string;
56 readonly args: ReadonlyArray<string>;
57 readonly options: ChildProcess.CommandOptions;
59​
60interface TargetPathAndPosition {
61 readonly path: string;
62 readonly line: string;
63 readonly column: Option.Option<string>;
65​
66// cmd shims reparse %* after escaping is gone; newlines and quotes can expose shell operators.
67const WINDOWS_SHIM_UNSAFE_ARG_PATTERN = /[\u0000-\u001f\u007f"]/;
68const TARGET_WITH_POSITION_PATTERN = /^(.*?):(\d+)(?::(\d+))?$/;
69const POWERSHELL_ARGUMENTS_PREFIX = [
70 "-NoProfile",
71 "-NonInteractive",
72 "-ExecutionPolicy",
73 "Bypass",
74 "-EncodedCommand",
75] as const;
76​
77// Detached Windows PowerShell exits 0 without executing; only WSL interop keeps detached launches.
78const WINDOWS_POWERSHELL_DETACHED = false;
79​
80const DETACHED_IGNORE_STDIO_OPTIONS = {
81 detached: true,
82 stdin: "ignore",
83 stdout: "ignore",
84 stderr: "ignore",
85} as const satisfies ChildProcess.CommandOptions;
86​
87const compactEnv = (input: Record<string, Option.Option<string>>): NodeJS.ProcessEnv =>
88 Object.fromEntries(
89 Object.entries(input).flatMap(([key, value]) =>
90 Option.match(value, {
91 onNone: () => [],
92 onSome: (resolved) => [[key, resolved]],
93 }),
94 ),
95 );
96​
97const BrowserLaunchEnvConfig = Config.all({
98 SYSTEMROOT: Config.String("SYSTEMROOT").pipe(Config.option),
99 windir: Config.String("windir").pipe(Config.option),
100 WSL_DISTRO_NAME: Config.String("WSL_DISTRO_NAME").pipe(Config.option),
101 WSL_INTEROP: Config.String("WSL_INTEROP").pipe(Config.option),
102 SSH_CONNECTION: Config.String("SSH_CONNECTION").pipe(Config.option),
103 SSH_TTY: Config.String("SSH_TTY").pipe(Config.option),
104 container: Config.String("container").pipe(Config.option),
105 DISPLAY: Config.String("DISPLAY").pipe(Config.option),
106 WAYLAND_DISPLAY: Config.String("WAYLAND_DISPLAY").pipe(Config.option),
107}).pipe(Config.map(compactEnv));
108​
109const CommandLookupEnvConfig = Config.all({
110 PATH: Config.String("PATH").pipe(Config.option),
111 Path: Config.String("Path").pipe(Config.option),
112 path: Config.String("path").pipe(Config.option),
113 PATHEXT: Config.String("PATHEXT").pipe(Config.option),
114 HOME: Config.String("HOME").pipe(Config.option),
115 LOCALAPPDATA: Config.String("LOCALAPPDATA").pipe(Config.option),
116 ProgramFiles: Config.String("ProgramFiles").pipe(Config.option),
117 ProgramW6432: Config.String("ProgramW6432").pipe(Config.option),
118 XDG_DATA_HOME: Config.String("XDG_DATA_HOME").pipe(Config.option),
119 "ProgramFiles(x86)": Config.String("ProgramFiles(x86)").pipe(Config.option),
120}).pipe(Config.map(compactEnv));
121​
122const readBrowserLaunchEnv = BrowserLaunchEnvConfig.pipe(Effect.orElseSucceed(() => ({})));
123const readCommandLookupEnv = CommandLookupEnvConfig.pipe(Effect.orElseSucceed(() => ({})));
124​
125function parseTargetPathAndPosition(target: string): Option.Option<TargetPathAndPosition> {
126 const match = TARGET_WITH_POSITION_PATTERN.exec(target);
127 if (!match?.[1] || !match[2]) {
128 return Option.none();
129 }
130​
131 return Option.some({
132 path: match[1],
133 line: match[2],
134 column: Option.fromUndefinedOr(match[3]),
135 });
137​
138function resolveCommandEditorArgs(
139 editor: (typeof EDITORS)[number],
140 target: string,
141): ReadonlyArray<string> {
142 const parsedTarget = parseTargetPathAndPosition(target);
143​
144 switch (editor.launchStyle) {
145 case "direct-path":
146 return [target];
147 case "goto":
148 return Option.isSome(parsedTarget) ? ["--goto", target] : [target];
149 case "line-column":
150 return Option.match(parsedTarget, {
151 onNone: () => [target],
152 onSome: ({ path, line, column }) => [
153 "--line",
154 line,
155 // JetBrains IDEs count `--column` from 0; targets count columns from 1.
156 ...Option.match(column, {
157 onNone: () => [],
158 onSome: (value) => ["--column", String(Math.max(0, Number(value) - 1))],
159 }),
160 path,
161 ],
162 });
163 }
165​
166function encodeUtf16LeBase64(input: string): string {
167 const bytes = new Uint8Array(input.length * 2);
168 for (let index = 0; index < input.length; index += 1) {
169 const code = input.charCodeAt(index);
170 bytes[index * 2] = code & 0xff;
171 bytes[index * 2 + 1] = code >>> 8;
172 }
173 return Base64.encode(bytes);
175​
176function escapePowerShellStringLiteral(input: string): string {
177 return `'${input.replaceAll("'", "''")}'`;
179​
180function resolvePowerShellPath(env: NodeJS.ProcessEnv = {}): string {
181 return `${env.SYSTEMROOT || env.windir || String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;
183​
184function resolveWslPowerShellPath(): string {
185 return "/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe";
187​
188// WSL automount roots vary; resolve PowerShell via PATH to match launchEditor's availability check.
189const WSL_POWERSHELL_COMMAND = "powershell.exe";
190​
191function shouldUseWindowsHostFromWsl(
192 platform: NodeJS.Platform,
193 env: NodeJS.ProcessEnv = {},
194): boolean {
195 return (
196 platform === "linux" &&
197 (env.WSL_DISTRO_NAME !== undefined || env.WSL_INTEROP !== undefined) &&
198 env.SSH_CONNECTION === undefined &&
199 env.SSH_TTY === undefined &&
200 env.container === undefined
201 );
203​
204function resolveWindowsBrowserLaunch(
205 target: string,
206 command: string,
207 detached: boolean,
208): ProcessLaunch {
209 const encodedCommand = encodeUtf16LeBase64(
210 `$ProgressPreference = 'SilentlyContinue'; Start ${escapePowerShellStringLiteral(target)}`,
211 );
212 return {
213 command,
214 args: [...POWERSHELL_ARGUMENTS_PREFIX, encodedCommand],
215 options: {
216 detached,
217 shell: false,
218 stdin: "ignore",
219 stdout: "ignore",
220 stderr: "ignore",
221 },
222 };
224​
225function hasGraphicalLinuxSession(env: NodeJS.ProcessEnv): boolean {
226 return [env.DISPLAY, env.WAYLAND_DISPLAY].some(
227 (value) => value !== undefined && value.trim().length > 0,
228 );
230​
231function fileManagerCommandForPlatform(
232 platform: NodeJS.Platform,
233 env: NodeJS.ProcessEnv,
234): string | undefined {
235 switch (platform) {
236 case "darwin":
237 return "open";
238 case "win32":
239 return "explorer";
240 default:
241 if (shouldUseWindowsHostFromWsl(platform, env)) {
242 return env.WSL_DISTRO_NAME?.trim() ? "explorer.exe" : undefined;
243 }
244 return hasGraphicalLinuxSession(env) ? "xdg-open" : undefined;
245 }
247​
248// xdg-open needs an inode/directory handler or detached launches silently fail.
249// Bound xdg-mime below discovery's timeout so a hung probe drops only the file manager.
250const LINUX_DIRECTORY_HANDLER_PROBE_TIMEOUT = "2 seconds";
251​
252const hasUsableLinuxDirectoryHandler = Effect.fn("externalLauncher.hasUsableLinuxDirectoryHandler")(
253 function* (
254 env: NodeJS.ProcessEnv,
255 ): Effect.fn.Return<
256 boolean,
257 never,
258 FileSystem.FileSystem | Path.Path | ChildProcessSpawner.ChildProcessSpawner
259 > {
260 if (!(yield* isCommandAvailable("xdg-mime", { env }))) {
261 return false;
262 }
263​
264 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
265 return yield* spawner
266 .spawn(
267 ChildProcess.make("xdg-mime", ["query", "default", "inode/directory"], {
268 stdin: "ignore",
269 stderr: "ignore",
270 }),
271 )
272 .pipe(
273 Effect.flatMap((handle) =>
274 Effect.all([handle.stdout.pipe(Stream.decodeText(), Stream.mkString), handle.exitCode], {
275 concurrency: "unbounded",
276 }),
277 ),
278 Effect.map(([stdout, exitCode]) => exitCode === 0 && stdout.trim().length > 0),
279 Effect.scoped,
280 Effect.timeout(LINUX_DIRECTORY_HANDLER_PROBE_TIMEOUT),
281 Effect.orElseSucceed(() => false),
282 );
283 },
284);
285​
286const isUsableFileManagerCommand = Effect.fn("externalLauncher.isUsableFileManagerCommand")(
287 function* (
288 command: string,
289 env: NodeJS.ProcessEnv,
290 ): Effect.fn.Return<
291 boolean,
292 never,
293 FileSystem.FileSystem | Path.Path | ChildProcessSpawner.ChildProcessSpawner
294 > {
295 if (!(yield* isCommandAvailable(command, { env }))) {
296 return false;
297 }
298 return command !== "xdg-open" || (yield* hasUsableLinuxDirectoryHandler(env));
299 },
300);
301​
302// WSL may lack Explorer on PATH or a distro name while WSLg still offers a Linux file manager.
303const resolveUsableFileManagerCommand = Effect.fn(
304 "externalLauncher.resolveUsableFileManagerCommand",
305)(function* (
306 platform: NodeJS.Platform,
307 env: NodeJS.ProcessEnv,
308): Effect.fn.Return<
309 string | undefined,
310 never,
311 FileSystem.FileSystem | Path.Path | ChildProcessSpawner.ChildProcessSpawner
312> {
313 const command = fileManagerCommandForPlatform(platform, env);
314 if (command !== undefined && (yield* isUsableFileManagerCommand(command, env))) {
315 return command;
316 }
317 if (
318 shouldUseWindowsHostFromWsl(platform, env) &&
319 hasGraphicalLinuxSession(env) &&
320 (yield* isUsableFileManagerCommand("xdg-open", env))
321 ) {
322 return "xdg-open";
323 }
324 return undefined;
325});
326​
327// Reveal uses PowerShell on Windows/WSL, so probe it separately from Explorer availability.
328// Linux relies on the file-manager gate's handler probe; WSL re-probes because the gate may use Explorer.
329const fileManagerRevealKindForPlatform = Effect.fn(
330 "externalLauncher.fileManagerRevealKindForPlatform",
331)(function* (
332 platform: NodeJS.Platform,
333 env: NodeJS.ProcessEnv,
334): Effect.fn.Return<
335 FileManagerRevealKind | undefined,
336 never,
337 FileSystem.FileSystem | Path.Path | ChildProcessSpawner.ChildProcessSpawner
338> {
339 if (platform === "darwin") return "finder";
340 if (platform === "win32") {
341 return (yield* isCommandAvailable(resolvePowerShellPath(env), { env }))
342 ? "file-explorer"
343 : undefined;
344 }
345 if (shouldUseWindowsHostFromWsl(platform, env)) {
346 if (
347 env.WSL_DISTRO_NAME?.trim() &&
348 (yield* isCommandAvailable("explorer.exe", { env })) &&
349 (yield* isCommandAvailable(WSL_POWERSHELL_COMMAND, { env }))
350 ) {
351 return "file-explorer";
352 }
353 return hasGraphicalLinuxSession(env) && (yield* isUsableFileManagerCommand("xdg-open", env))
354 ? "files"
355 : undefined;
356 }
357 return hasGraphicalLinuxSession(env) ? "files" : undefined;
358});
359​
360function resolveWslFileManagerPath(target: string, distroName: string): string {
361 const relativePath = target.replace(/^\/+/, "").replaceAll("/", "\\");
362 return `\\\\wsl.localhost\\${distroName}${relativePath.length > 0 ? `\\${relativePath}` : ""}`;
364​
365function buildBrowserLaunch(
366 target: string,
367 platform: NodeJS.Platform,
368 env: NodeJS.ProcessEnv = {},
369): ProcessLaunch {
370 if (platform === "darwin") {
371 return {
372 command: "open",
373 args: [target],
374 options: DETACHED_IGNORE_STDIO_OPTIONS,
375 };
376 }
377​
378 if (platform === "win32") {
379 return resolveWindowsBrowserLaunch(
380 target,
381 resolvePowerShellPath(env),
382 WINDOWS_POWERSHELL_DETACHED,
383 );
384 }
385​
386 if (shouldUseWindowsHostFromWsl(platform, env)) {
387 return resolveWindowsBrowserLaunch(target, resolveWslPowerShellPath(), true);
388 }
389​
390 return {
391 command: "xdg-open",
392 args: [target],
393 options: DETACHED_IGNORE_STDIO_OPTIONS,
394 };
396​
397const buildAvailableEditors = Effect.fn("externalLauncher.buildAvailableEditors")(function* (
398 platform: NodeJS.Platform,
399 env: NodeJS.ProcessEnv,
400): Effect.fn.Return<
401 ReadonlyArray<EditorId>,
402 never,
403 FileSystem.FileSystem | Path.Path | ChildProcessSpawner.ChildProcessSpawner
404> {
405 const available: EditorId[] = [];
406​
407 for (const editor of EDITORS) {
408 if (editor.commands === null) {
409 if ((yield* resolveUsableFileManagerCommand(platform, env)) !== undefined) {
410 available.push(editor.id);
411 }
412 continue;
413 }
414​
415 const command = yield* resolveEditorCommand(editor, env);
416 if (Option.isSome(command)) {
417 available.push(editor.id);
418 }
419 }
420​
421 return available;
422});
423​
424const resolveBrowserLaunch = Effect.fn("externalLauncher.resolveBrowserLaunch")(function* (
425 target: string,
426) {
427 const platform = yield* HostProcess.Platform;
428 const env = yield* readBrowserLaunchEnv;
429 return buildBrowserLaunch(target, platform, env);
430});
431​
432const resolveAvailableEditors = Effect.fn("externalLauncher.resolveAvailableEditors")(function* () {
433 const platform = yield* HostProcess.Platform;
434 const env = { ...(yield* readBrowserLaunchEnv), ...(yield* readCommandLookupEnv) };
435 return yield* buildAvailableEditors(platform, env).pipe(withPathDirectoryListings);
436});
437​
438const resolveFileManagerRevealKind = Effect.fn("externalLauncher.resolveFileManagerRevealKind")(
439 function* () {
440 const platform = yield* HostProcess.Platform;
441 const env = { ...(yield* readBrowserLaunchEnv), ...(yield* readCommandLookupEnv) };
442 return yield* fileManagerRevealKindForPlatform(platform, env);
443 },
444);
445​
446const EDITOR_DISCOVERY_CACHE_TTL = "60 seconds";
447​
448export class ExternalLauncher extends Context.Service<
449 ExternalLauncher,
450 {
451 readonly resolveAvailableEditors: () => Effect.Effect<ReadonlyArray<EditorId>>;
452 /** Requires file-manager in resolveAvailableEditors; Linux relies on its directory-handler probe. */
453 readonly resolveFileManagerRevealKind: () => Effect.Effect<FileManagerRevealKind | undefined>;
454 readonly launchBrowser: (target: string) => Effect.Effect<void, ExternalLauncherError>;
455 readonly launchEditor: (input: LaunchEditorInput) => Effect.Effect<void, ExternalLauncherError>;
456 }
457>()("t3/process/externalLauncher") {}
458​
459const resolveEditorLaunch = Effect.fn("resolveEditorLaunch")(function* (
460 input: LaunchEditorInput,
461): Effect.fn.Return<
462 EditorLaunch,
463 ExternalLauncherError,
464 FileSystem.FileSystem | Path.Path | ChildProcessSpawner.ChildProcessSpawner
465> {
466 const platform = yield* HostProcess.Platform;
467 const env = { ...(yield* readBrowserLaunchEnv), ...(yield* readCommandLookupEnv) };
468 yield* Effect.annotateCurrentSpan({
469 "externalLauncher.editor": input.editor,
470 "externalLauncher.cwd": input.cwd,
471 "externalLauncher.platform": platform,
472 });
473 const editorDef = EDITORS.find((editor) => editor.id === input.editor);
474 if (!editorDef) {
475 return yield* new ExternalLauncherUnknownEditorError({ editor: input.editor });
476 }
477​
478 if (editorDef.commands) {
479 const { command, baseArgs } = Option.getOrElse(
480 yield* resolveEditorCommand(editorDef, env),
481 () => ({
482 command: editorDef.commands[0],
483 baseArgs: "baseArgs" in editorDef ? editorDef.baseArgs : [],
484 }),
485 );
486 return {
487 editor: editorDef.id,
488 target: input.cwd,
489 command,
490 args: [...baseArgs, ...resolveCommandEditorArgs(editorDef, input.cwd)],
491 };
492 }
493​
494 if (editorDef.id !== "file-manager") {
495 return yield* new ExternalLauncherUnsupportedEditorError({ editor: input.editor });
496 }
497​
498 const command = yield* resolveUsableFileManagerCommand(platform, env);
499 if (command === undefined) {
500 return yield* new ExternalLauncherUnsupportedEditorError({ editor: input.editor });
501 }
502​
503 if (input.reveal === true) {
504 return yield* resolveFileManagerRevealLaunch(input.cwd, platform, env, command);
505 }
506​
507 return {
508 editor: editorDef.id,
509 target: input.cwd,
510 command,
511 args:
512 command === "explorer.exe" && env.WSL_DISTRO_NAME !== undefined
513 ? [resolveWslFileManagerPath(input.cwd, env.WSL_DISTRO_NAME)]
514 : platform === "win32"
515 ? // Explorer interprets / as a switch and silently opens a fallback folder.
516 [normalizeWindowsFileManagerPath(input.cwd)]
517 : [input.cwd],
518 };
519});
520​
521// A replacement manager registers a default Directory shell verb; stock Windows
522// uses "none". Explorer needs its /select argument passed verbatim through
523// PowerShell because Node's argument quoting changes how Explorer parses it.
524function buildFileManagerRevealPowerShellSource(target: string, parent: string): string {
525 const literal = escapePowerShellStringLiteral(target);
526 return `$ProgressPreference = 'SilentlyContinue'; $folderVerb = (Get-ItemProperty -LiteralPath 'Registry::HKEY_CLASSES_ROOT\\Directory\\shell' -ErrorAction SilentlyContinue).'(default)'; if ($folderVerb -and $folderVerb -ne 'none') { Invoke-Item -LiteralPath ${escapePowerShellStringLiteral(parent)} } else { Start-Process 'explorer.exe' -ArgumentList ('/select,"' + ${literal} + '"') }`;
528​
529function powerShellFileManagerLaunch(
530 target: string,
531 source: string,
532 powershellCommand: string,
533): EditorLaunch {
534 return {
535 editor: "file-manager",
536 target,
537 command: powershellCommand,
538 args: [...POWERSHELL_ARGUMENTS_PREFIX, encodeUtf16LeBase64(source)],
539 };
541​
542function normalizeWindowsFileManagerPath(target: string): string {
543 return target.replaceAll("/", "\\");
545​
546const resolveFileManagerRevealLaunch = Effect.fn("resolveFileManagerRevealLaunch")(function* (
547 target: string,
548 platform: NodeJS.Platform,
549 env: NodeJS.ProcessEnv,
550 command: string,
551): Effect.fn.Return<
552 EditorLaunch,
553 never,
554 FileSystem.FileSystem | Path.Path | ChildProcessSpawner.ChildProcessSpawner
555> {
556 if (platform === "darwin") {
557 return { editor: "file-manager", target, command: "open", args: ["-R", target] };
558 }
559​
560 if (platform === "win32") {
561 const path = yield* Path.Path.pipe(Effect.provide(NodePath.layerWin32));
562 const windowsTarget = normalizeWindowsFileManagerPath(target);
563 return {
564 ...powerShellFileManagerLaunch(
565 target,
566 buildFileManagerRevealPowerShellSource(windowsTarget, path.dirname(windowsTarget)),
567 resolvePowerShellPath(env),
568 ),
569 detached: WINDOWS_POWERSHELL_DETACHED,
570 };
571 }
572​
573 if (
574 command === "explorer.exe" &&
575 shouldUseWindowsHostFromWsl(platform, env) &&
576 env.WSL_DISTRO_NAME !== undefined
577 ) {
578 const explorerTarget = resolveWslFileManagerPath(target, env.WSL_DISTRO_NAME);
579 if (yield* isCommandAvailable(WSL_POWERSHELL_COMMAND, { env })) {
580 // WSL names may contain quotes that Explorer's /select cannot encode.
581 // Open the parent through the shell so replacement managers still apply.
582 const path = yield* Path.Path;
583 // .NET path parsing rejects characters that are legal in WSL filenames.
584 const parent = resolveWslFileManagerPath(path.dirname(target), env.WSL_DISTRO_NAME);
585 const source = explorerTarget.includes('"')
586 ? `Invoke-Item -LiteralPath ${escapePowerShellStringLiteral(parent)}`
587 : buildFileManagerRevealPowerShellSource(explorerTarget, parent);
588 return powerShellFileManagerLaunch(target, source, WSL_POWERSHELL_COMMAND);
589 }
590 if (hasGraphicalLinuxSession(env) && (yield* isUsableFileManagerCommand("xdg-open", env))) {
591 const path = yield* Path.Path;
592 return { editor: "file-manager", target, command: "xdg-open", args: [path.dirname(target)] };
593 }
594 const path = yield* Path.Path;
595 return {
596 editor: "file-manager",
597 target,
598 command: "explorer.exe",
599 args: [resolveWslFileManagerPath(path.dirname(target), env.WSL_DISTRO_NAME)],
600 };
601 }
602​
603 const path = yield* Path.Path;
604 return { editor: "file-manager", target, command, args: [path.dirname(target)] };
605});
606​
607const tryRevealLinuxItem = Effect.fn("externalLauncher.tryRevealLinuxItem")(
608 function* (target: string) {
609 const env = yield* readCommandLookupEnv;
610 if (!(yield* isCommandAvailable("gdbus", { env }))) return false;
611​
612 const path = yield* Path.Path;
613 const uri = yield* path.toFileUrl(target);
614 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
615 const exitCode = yield* spawner.exitCode(
616 ChildProcess.make(
617 "gdbus",
618 [
619 "call",
620 "--session",
621 "--dest",
622 "org.freedesktop.FileManager1",
623 "--object-path",
624 "/org/freedesktop/FileManager1",
625 "--method",
626 "org.freedesktop.FileManager1.ShowItems",
627 // File URLs percent-encode the double quotes and backslashes GVariant would interpret.
628 `["${uri.href}"]`,
629 "",
630 ],
631 {
632 stdin: "ignore",
633 stdout: "ignore",
634 stderr: "ignore",
635 // Timeout waits for scoped cleanup, even if the helper ignores SIGTERM.
636 forceKillAfter: "1 second",
637 },
638 ),
639 );
640 return exitCode === 0;
641 },
642 Effect.timeout("2 seconds"),
643 Effect.catchTags({
644 BadArgument: () => Effect.succeed(false),
645 PlatformError: () => Effect.succeed(false),
646 TimeoutError: () => Effect.succeed(false),
647 }),
648);
649​
650const launchEditor = Effect.fn("externalLauncher.launchEditor")(function* (
651 input: LaunchEditorInput,
652) {
653 const launch = yield* resolveEditorLaunch(input);
654 if (
655 input.editor === "file-manager" &&
656 input.reveal === true &&
657 launch.command === "xdg-open" &&
658 (yield* HostProcess.Platform) === "linux" &&
659 (yield* tryRevealLinuxItem(launch.target))
660 ) {
661 return;
662 }
663 yield* launchEditorProcess(launch);
664});
665​
666const GRAPHICAL_SESSION_ENV_KEYS: ReadonlySet<string> = new Set([
667 "DISPLAY",
668 "WAYLAND_DISPLAY",
669 "XAUTHORITY",
670]);
671​
672// The user manager's environment over D-Bus. `systemctl show-environment` would
673// shell-quote values with spaces as $'...', while this JSON carries them raw.
674const decodeManagerEnvironment = Schema.decodeUnknownEffect(
675 Schema.fromJsonString(Schema.Struct({ data: Schema.Array(Schema.String) })),
676);
677​
678// Boot services miss the desktop environment imported later into the systemd user manager.
679const readGraphicalSessionEnv = Effect.fn("externalLauncher.readGraphicalSessionEnv")(
680 function* () {
681 const hostEnv = yield* HostProcess.Environment;
682 if ((yield* HostProcess.Platform) !== "linux" || hasGraphicalLinuxSession(hostEnv)) {
683 return {};
684 }
685 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
686 const output = yield* spawner.string(
687 ChildProcess.make(
688 "busctl",
689 [
690 "--user",
691 "--json=short",
692 "get-property",
693 "org.freedesktop.systemd1",
694 "/org/freedesktop/systemd1",
695 "org.freedesktop.systemd1.Manager",
696 "Environment",
697 ],
698 { stdin: "ignore", stderr: "ignore" },
699 ),
700 );
701 const { data } = yield* decodeManagerEnvironment(output);
702 return Object.fromEntries(
703 data.flatMap((line) => {
704 const separator = line.indexOf("=");
705 const key = line.slice(0, separator);
706 return separator > 0 && GRAPHICAL_SESSION_ENV_KEYS.has(key)
707 ? [[key, line.slice(separator + 1)]]
708 : [];
709 }),
710 );
711 },
712 Effect.timeout("2 seconds"),
713 Effect.orElseSucceed((): NodeJS.ProcessEnv => ({})),
714);
715​
716const launchAndUnref = Effect.fn("externalLauncher.launchAndUnref")(function* (
717 launch: ProcessLaunch,
718 onError: (cause: unknown) => ExternalLauncherError,
719): Effect.fn.Return<void, ExternalLauncherError, ChildProcessSpawner.ChildProcessSpawner> {
720 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
721 // Inherited ELECTRON_RUN_AS_NODE would make Electron apps opened by this launcher run as Node and exit.
722 const { ELECTRON_RUN_AS_NODE: _runAsNode, ...env } = yield* HostProcess.Environment;
723 const command = ChildProcess.make(launch.command, launch.args, {
724 ...launch.options,
725 env: { ...env, ...launch.options.env },
726 extendEnv: false,
727 });
728​
729 yield* spawner.spawn(command).pipe(
730 Effect.flatMap((handle) => handle.unref),
731 Effect.asVoid,
732 Effect.scoped,
733 Effect.mapError(onError),
734 );
735});
736​
737const launchBrowser = Effect.fn("externalLauncher.launchBrowser")(function* (
738 target: string,
739): Effect.fn.Return<void, ExternalLauncherError, ChildProcessSpawner.ChildProcessSpawner> {
740 const launch = yield* resolveBrowserLaunch(target);
741 return yield* launchAndUnref(
742 launch,
743 (cause) =>
744 new ExternalLauncherBrowserSpawnError({
745 target,
746 command: launch.command,
747 args: launch.args,
748 cause,
749 }),
750 );
751});
752​
753const launchEditorProcess = Effect.fn("externalLauncher.launchEditorProcess")(function* (
754 launch: EditorLaunch,
755): Effect.fn.Return<
756 void,
757 ExternalLauncherError,
758 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
759> {
760 const env = yield* readCommandLookupEnv;
761 if (!(yield* isCommandAvailable(launch.command, { env }))) {
762 return yield* new ExternalLauncherCommandNotFoundError({
763 editor: launch.editor,
764 command: launch.command,
765 });
766 }
767​
768 const spawnCommand = yield* resolveSpawnCommand(launch.command, launch.args, { env });
769 if (spawnCommand.shell && launch.args.some((arg) => WINDOWS_SHIM_UNSAFE_ARG_PATTERN.test(arg))) {
770 return yield* new ExternalLauncherUnsupportedTargetError({ editor: launch.editor });
771 }
772 yield* launchAndUnref(
773 {
774 command: spawnCommand.command,
775 args: spawnCommand.args,
776 options: {
777 detached: launch.detached ?? true,
778 shell: spawnCommand.shell,
779 env: yield* readGraphicalSessionEnv(),
780 stdin: "ignore",
781 stdout: "ignore",
782 stderr: "ignore",
783 },
784 },
785 (cause) =>
786 new ExternalLauncherEditorSpawnError({
787 editor: launch.editor,
788 target: launch.target,
789 command: spawnCommand.command,
790 args: spawnCommand.args,
791 cause,
792 }),
793 );
794});
795​
796/** @public */
797export const make = Effect.gen(function* () {
798 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
799 const fileSystem = yield* FileSystem.FileSystem;
800 const path = yield* Path.Path;
801​
802 const provideCommandResolutionServices = <A, E, R>(
803 effect: Effect.Effect<A, E, R | FileSystem.FileSystem | Path.Path>,
804 ) =>
805 effect.pipe(
806 Effect.provideService(FileSystem.FileSystem, fileSystem),
807 Effect.provideService(Path.Path, path),
808 );
809​
810 const cachedAvailableEditors = yield* makeStaleWhileRevalidate(
811 provideCommandResolutionServices(resolveAvailableEditors()).pipe(
812 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
813 ),
814 EDITOR_DISCOVERY_CACHE_TTL,
815 );
816 const cachedFileManagerRevealKind = yield* makeStaleWhileRevalidate(
817 provideCommandResolutionServices(resolveFileManagerRevealKind()).pipe(
818 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
819 ),
820 EDITOR_DISCOVERY_CACHE_TTL,
821 );
822​
823 // Forwarders retain the underlying launcher and discovery spans.
824 return ExternalLauncher.of({
825 resolveAvailableEditors: Effect.fnUntraced(function* () {
826 return yield* cachedAvailableEditors;
827 }),
828 resolveFileManagerRevealKind: Effect.fnUntraced(function* () {
829 return yield* cachedFileManagerRevealKind;
830 }),
831 launchBrowser: Effect.fnUntraced(
832 function* (target) {
833 return yield* launchBrowser(target);
834 },
835 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
836 ),
837 launchEditor: Effect.fnUntraced(
838 function* (input) {
839 return yield* provideCommandResolutionServices(launchEditor(input));
840 },
841 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
842 ),
843 });
844});
845​
846export const layer = Layer.effect(ExternalLauncher, make);