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

externalLauncher.ts

814 lines27.5 KB

1import {
2 EDITORS,
3 ExternalLauncherError,
4 ExternalLauncherBrowserSpawnError,
5 ExternalLauncherCommandNotFoundError,
6 ExternalLauncherEditorSpawnError,
7 ExternalLauncherUnknownEditorError,
8 ExternalLauncherUnsupportedEditorError,
9 ExternalLauncherUnsupportedTargetError,
10 type EditorId,
11 type FileManagerRevealKind,
12 type LaunchEditorInput,
13} from "@t3tools/contracts";
14import { resolveEditorCommand } from "@t3tools/shared/editor";
15import * as HostProcess from "@t3tools/shared/HostProcess";
16import {
17 isCommandAvailable,
18 resolveSpawnCommand,
19 withPathDirectoryListings,
20} from "@t3tools/shared/shell";
21import * as Clock from "effect/Clock";
22import * as Config from "effect/Config";
23import * as Context from "effect/Context";
24import * as Deferred from "effect/Deferred";
25import * as Effect from "effect/Effect";
26import * as Base64 from "effect/encoding/Base64";
27import * as Exit from "effect/Exit";
28import * as FileSystem from "effect/FileSystem";
29import * as Layer from "effect/Layer";
30import * as Option from "effect/Option";
31import * as Path from "effect/Path";
32import * as Ref from "effect/Ref";
33import * as Scope from "effect/Scope";
34import * as Stream from "effect/Stream";
35import * as ChildProcess from "effect/process/ChildProcess";
36import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
37​
38export {
39 ExternalLauncherError,
40 ExternalLauncherBrowserSpawnError,
41 ExternalLauncherCommandNotFoundError,
42 ExternalLauncherEditorSpawnError,
43 ExternalLauncherUnknownEditorError,
44 ExternalLauncherUnsupportedEditorError,
45 ExternalLauncherUnsupportedTargetError,
46} from "@t3tools/contracts";
47export type { LaunchEditorInput };
48interface EditorLaunch {
49 readonly editor: EditorId;
50 readonly target: string;
51 readonly command: string;
52 readonly args: ReadonlyArray<string>;
53 readonly detached?: boolean;
55​
56interface ProcessLaunch {
57 readonly command: string;
58 readonly args: ReadonlyArray<string>;
59 readonly options: ChildProcess.CommandOptions;
61​
62interface TargetPathAndPosition {
63 readonly path: string;
64 readonly line: string;
65 readonly column: Option.Option<string>;
67​
68/**
69 * Windows command shims (`code.cmd`) forward arguments through `%*`, which
70 * cmd.exe parses a second time after the first escaping layer is gone: a
71 * line break ends the command there, and a double quote closes the quoting
72 * that keeps `&` or `|` literal. Neither can occur in a Windows path.
73 */
74// oxlint-disable-next-line no-control-regex
75const WINDOWS_SHIM_UNSAFE_ARG_PATTERN = /[\u0000-\u001f\u007f"]/;
76const TARGET_WITH_POSITION_PATTERN = /^(.*?):(\d+)(?::(\d+))?$/;
77const POWERSHELL_ARGUMENTS_PREFIX = [
78 "-NoProfile",
79 "-NonInteractive",
80 "-ExecutionPolicy",
81 "Bypass",
82 "-EncodedCommand",
83] as const;
84​
85// Windows PowerShell started with DETACHED_PROCESS exits 0 without running its
86// command, so native Windows launches through it stay attached. WSL interop
87// PowerShell starts from a Linux process and keeps the detached launch.
88const WINDOWS_POWERSHELL_DETACHED = false;
89​
90const DETACHED_IGNORE_STDIO_OPTIONS = {
91 detached: true,
92 stdin: "ignore",
93 stdout: "ignore",
94 stderr: "ignore",
95} as const satisfies ChildProcess.CommandOptions;
96​
97const compactEnv = (input: Record<string, Option.Option<string>>): NodeJS.ProcessEnv =>
98 Object.fromEntries(
99 Object.entries(input).flatMap(([key, value]) =>
100 Option.match(value, {
101 onNone: () => [],
102 onSome: (resolved) => [[key, resolved]],
103 }),
104 ),
105 );
106​
107const BrowserLaunchEnvConfig = Config.all({
108 SYSTEMROOT: Config.String("SYSTEMROOT").pipe(Config.option),
109 windir: Config.String("windir").pipe(Config.option),
110 WSL_DISTRO_NAME: Config.String("WSL_DISTRO_NAME").pipe(Config.option),
111 WSL_INTEROP: Config.String("WSL_INTEROP").pipe(Config.option),
112 SSH_CONNECTION: Config.String("SSH_CONNECTION").pipe(Config.option),
113 SSH_TTY: Config.String("SSH_TTY").pipe(Config.option),
114 container: Config.String("container").pipe(Config.option),
115 DISPLAY: Config.String("DISPLAY").pipe(Config.option),
116 WAYLAND_DISPLAY: Config.String("WAYLAND_DISPLAY").pipe(Config.option),
117}).pipe(Config.map(compactEnv));
118​
119const CommandLookupEnvConfig = Config.all({
120 PATH: Config.String("PATH").pipe(Config.option),
121 Path: Config.String("Path").pipe(Config.option),
122 path: Config.String("path").pipe(Config.option),
123 PATHEXT: Config.String("PATHEXT").pipe(Config.option),
124 HOME: Config.String("HOME").pipe(Config.option),
125 LOCALAPPDATA: Config.String("LOCALAPPDATA").pipe(Config.option),
126 ProgramFiles: Config.String("ProgramFiles").pipe(Config.option),
127 ProgramW6432: Config.String("ProgramW6432").pipe(Config.option),
128 XDG_DATA_HOME: Config.String("XDG_DATA_HOME").pipe(Config.option),
129 "ProgramFiles(x86)": Config.String("ProgramFiles(x86)").pipe(Config.option),
130}).pipe(Config.map(compactEnv));
131​
132const readBrowserLaunchEnv = BrowserLaunchEnvConfig.pipe(Effect.orElseSucceed(() => ({})));
133const readCommandLookupEnv = CommandLookupEnvConfig.pipe(Effect.orElseSucceed(() => ({})));
134​
135function parseTargetPathAndPosition(target: string): Option.Option<TargetPathAndPosition> {
136 const match = TARGET_WITH_POSITION_PATTERN.exec(target);
137 if (!match?.[1] || !match[2]) {
138 return Option.none();
139 }
140​
141 return Option.some({
142 path: match[1],
143 line: match[2],
144 column: Option.fromUndefinedOr(match[3]),
145 });
147​
148function resolveCommandEditorArgs(
149 editor: (typeof EDITORS)[number],
150 target: string,
151): ReadonlyArray<string> {
152 const parsedTarget = parseTargetPathAndPosition(target);
153​
154 switch (editor.launchStyle) {
155 case "direct-path":
156 return [target];
157 case "goto":
158 return Option.isSome(parsedTarget) ? ["--goto", target] : [target];
159 case "line-column":
160 return Option.match(parsedTarget, {
161 onNone: () => [target],
162 onSome: ({ path, line, column }) => [
163 "--line",
164 line,
165 ...Option.match(column, {
166 onNone: () => [],
167 onSome: (value) => ["--column", value],
168 }),
169 path,
170 ],
171 });
172 }
174​
175function encodeUtf16LeBase64(input: string): string {
176 const bytes = new Uint8Array(input.length * 2);
177 for (let index = 0; index < input.length; index += 1) {
178 const code = input.charCodeAt(index);
179 bytes[index * 2] = code & 0xff;
180 bytes[index * 2 + 1] = code >>> 8;
181 }
182 return Base64.encode(bytes);
184​
185function escapePowerShellStringLiteral(input: string): string {
186 return `'${input.replaceAll("'", "''")}'`;
188​
189function resolvePowerShellPath(env: NodeJS.ProcessEnv = {}): string {
190 return `${env.SYSTEMROOT || env.windir || String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;
192​
193function resolveWslPowerShellPath(): string {
194 return "/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe";
196​
197// File reveals from WSL resolve PowerShell through the interop PATH rather
198// than the fixed /mnt/c mount: the automount root is configurable, and a
199// PATH-resolved command keeps the advertised capability aligned with the
200// availability check `launchEditor` performs before spawning.
201const WSL_POWERSHELL_COMMAND = "powershell.exe";
202​
203function shouldUseWindowsHostFromWsl(
204 platform: NodeJS.Platform,
205 env: NodeJS.ProcessEnv = {},
206): boolean {
207 return (
208 platform === "linux" &&
209 (env.WSL_DISTRO_NAME !== undefined || env.WSL_INTEROP !== undefined) &&
210 env.SSH_CONNECTION === undefined &&
211 env.SSH_TTY === undefined &&
212 env.container === undefined
213 );
215​
216function resolveWindowsBrowserLaunch(
217 target: string,
218 command: string,
219 detached: boolean,
220): ProcessLaunch {
221 const encodedCommand = encodeUtf16LeBase64(
222 `$ProgressPreference = 'SilentlyContinue'; Start ${escapePowerShellStringLiteral(target)}`,
223 );
224 return {
225 command,
226 args: [...POWERSHELL_ARGUMENTS_PREFIX, encodedCommand],
227 options: {
228 detached,
229 shell: false,
230 stdin: "ignore",
231 stdout: "ignore",
232 stderr: "ignore",
233 },
234 };
236​
237function hasGraphicalLinuxSession(env: NodeJS.ProcessEnv): boolean {
238 return [env.DISPLAY, env.WAYLAND_DISPLAY].some(
239 (value) => value !== undefined && value.trim().length > 0,
240 );
242​
243function fileManagerCommandForPlatform(
244 platform: NodeJS.Platform,
245 env: NodeJS.ProcessEnv,
246): string | undefined {
247 switch (platform) {
248 case "darwin":
249 return "open";
250 case "win32":
251 return "explorer";
252 default:
253 if (shouldUseWindowsHostFromWsl(platform, env)) {
254 return env.WSL_DISTRO_NAME?.trim() ? "explorer.exe" : undefined;
255 }
256 return hasGraphicalLinuxSession(env) ? "xdg-open" : undefined;
257 }
259​
260// A graphical session variable plus an executable `xdg-open` does not prove
261// that opening a directory does anything: without an `inode/directory` MIME
262// handler, `xdg-open` exits nonzero after the launcher has already detached, so
263// the client would see a silent no-op. The probe carries its own timeout well
264// inside the scan timeout `server.getConfig` applies to editor discovery: that
265// outer timeout degrades to an empty editor list, so a hung `xdg-mime` (broken
266// D-Bus or desktop session) must cost only the file manager, not every
267// discovered editor.
268const LINUX_DIRECTORY_HANDLER_PROBE_TIMEOUT = "2 seconds";
269​
270const hasUsableLinuxDirectoryHandler = Effect.fn("externalLauncher.hasUsableLinuxDirectoryHandler")(
271 function* (
272 env: NodeJS.ProcessEnv,
273 ): Effect.fn.Return<
274 boolean,
275 never,
276 FileSystem.FileSystem | Path.Path | ChildProcessSpawner.ChildProcessSpawner
277 > {
278 if (!(yield* isCommandAvailable("xdg-mime", { env }))) {
279 return false;
280 }
281​
282 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
283 return yield* spawner
284 .spawn(
285 ChildProcess.make("xdg-mime", ["query", "default", "inode/directory"], {
286 stdin: "ignore",
287 stderr: "ignore",
288 }),
289 )
290 .pipe(
291 Effect.flatMap((handle) =>
292 Effect.all([handle.stdout.pipe(Stream.decodeText(), Stream.mkString), handle.exitCode], {
293 concurrency: "unbounded",
294 }),
295 ),
296 Effect.map(([stdout, exitCode]) => exitCode === 0 && stdout.trim().length > 0),
297 Effect.scoped,
298 Effect.timeout(LINUX_DIRECTORY_HANDLER_PROBE_TIMEOUT),
299 Effect.orElseSucceed(() => false),
300 );
301 },
302);
303​
304const isUsableFileManagerCommand = Effect.fn("externalLauncher.isUsableFileManagerCommand")(
305 function* (
306 command: string,
307 env: NodeJS.ProcessEnv,
308 ): Effect.fn.Return<
309 boolean,
310 never,
311 FileSystem.FileSystem | Path.Path | ChildProcessSpawner.ChildProcessSpawner
312 > {
313 if (!(yield* isCommandAvailable(command, { env }))) {
314 return false;
315 }
316 return command !== "xdg-open" || (yield* hasUsableLinuxDirectoryHandler(env));
317 },
318);
319​
320// WSL hosts prefer the Windows Explorer bridge, but interop can exist without
321// `explorer.exe` on PATH (appendWindowsPath=false) or without a distro name
322// while WSLg still provides a working Linux file manager, so they keep the
323// `xdg-open` fallback instead of losing the editor entirely.
324const resolveUsableFileManagerCommand = Effect.fn(
325 "externalLauncher.resolveUsableFileManagerCommand",
326)(function* (
327 platform: NodeJS.Platform,
328 env: NodeJS.ProcessEnv,
329): Effect.fn.Return<
330 string | undefined,
331 never,
332 FileSystem.FileSystem | Path.Path | ChildProcessSpawner.ChildProcessSpawner
333> {
334 const command = fileManagerCommandForPlatform(platform, env);
335 if (command !== undefined && (yield* isUsableFileManagerCommand(command, env))) {
336 return command;
337 }
338 if (
339 shouldUseWindowsHostFromWsl(platform, env) &&
340 hasGraphicalLinuxSession(env) &&
341 (yield* isUsableFileManagerCommand("xdg-open", env))
342 ) {
343 return "xdg-open";
344 }
345 return undefined;
346});
347​
348// Reveal on Windows and WSL runs through PowerShell (see
349// resolveFileManagerRevealLaunch), not the `explorer` command that gates the
350// file-manager editor itself, so the capability must probe the executables the
351// reveal actually spawns. Callers gate on file-manager availability first;
352// the Linux "files" kind relies on that gate for the directory-handler probe,
353// while the WSL fallback re-probes because its availability may have come
354// from the Explorer bridge instead.
355const fileManagerRevealKindForPlatform = Effect.fn(
356 "externalLauncher.fileManagerRevealKindForPlatform",
357)(function* (
358 platform: NodeJS.Platform,
359 env: NodeJS.ProcessEnv,
360): Effect.fn.Return<
361 FileManagerRevealKind | undefined,
362 never,
363 FileSystem.FileSystem | Path.Path | ChildProcessSpawner.ChildProcessSpawner
364> {
365 if (platform === "darwin") return "finder";
366 if (platform === "win32") {
367 return (yield* isCommandAvailable(resolvePowerShellPath(env), { env }))
368 ? "file-explorer"
369 : undefined;
370 }
371 if (shouldUseWindowsHostFromWsl(platform, env)) {
372 if (
373 env.WSL_DISTRO_NAME?.trim() &&
374 (yield* isCommandAvailable("explorer.exe", { env })) &&
375 (yield* isCommandAvailable(WSL_POWERSHELL_COMMAND, { env }))
376 ) {
377 return "file-explorer";
378 }
379 return hasGraphicalLinuxSession(env) && (yield* isUsableFileManagerCommand("xdg-open", env))
380 ? "files"
381 : undefined;
382 }
383 return hasGraphicalLinuxSession(env) ? "files" : undefined;
384});
385​
386function resolveWslFileManagerPath(target: string, distroName: string): string {
387 const relativePath = target.replace(/^\/+/, "").replaceAll("/", "\\");
388 return `\\\\wsl.localhost\\${distroName}${relativePath.length > 0 ? `\\${relativePath}` : ""}`;
390​
391function buildBrowserLaunch(
392 target: string,
393 platform: NodeJS.Platform,
394 env: NodeJS.ProcessEnv = {},
395): ProcessLaunch {
396 if (platform === "darwin") {
397 return {
398 command: "open",
399 args: [target],
400 options: DETACHED_IGNORE_STDIO_OPTIONS,
401 };
402 }
403​
404 if (platform === "win32") {
405 return resolveWindowsBrowserLaunch(
406 target,
407 resolvePowerShellPath(env),
408 WINDOWS_POWERSHELL_DETACHED,
409 );
410 }
411​
412 if (shouldUseWindowsHostFromWsl(platform, env)) {
413 return resolveWindowsBrowserLaunch(target, resolveWslPowerShellPath(), true);
414 }
415​
416 return {
417 command: "xdg-open",
418 args: [target],
419 options: DETACHED_IGNORE_STDIO_OPTIONS,
420 };
422​
423const buildAvailableEditors = Effect.fn("externalLauncher.buildAvailableEditors")(function* (
424 platform: NodeJS.Platform,
425 env: NodeJS.ProcessEnv,
426): Effect.fn.Return<
427 ReadonlyArray<EditorId>,
428 never,
429 FileSystem.FileSystem | Path.Path | ChildProcessSpawner.ChildProcessSpawner
430> {
431 const available: EditorId[] = [];
432​
433 for (const editor of EDITORS) {
434 if (editor.commands === null) {
435 if ((yield* resolveUsableFileManagerCommand(platform, env)) !== undefined) {
436 available.push(editor.id);
437 }
438 continue;
439 }
440​
441 const command = yield* resolveEditorCommand(editor, env);
442 if (Option.isSome(command)) {
443 available.push(editor.id);
444 }
445 }
446​
447 return available;
448});
449​
450const resolveBrowserLaunch = Effect.fn("externalLauncher.resolveBrowserLaunch")(function* (
451 target: string,
452) {
453 const platform = yield* HostProcess.Platform;
454 const env = yield* readBrowserLaunchEnv;
455 return buildBrowserLaunch(target, platform, env);
456});
457​
458const resolveAvailableEditors = Effect.fn("externalLauncher.resolveAvailableEditors")(function* () {
459 const platform = yield* HostProcess.Platform;
460 const env = { ...(yield* readBrowserLaunchEnv), ...(yield* readCommandLookupEnv) };
461 return yield* buildAvailableEditors(platform, env).pipe(withPathDirectoryListings);
462});
463​
464const resolveFileManagerRevealKind = Effect.fn("externalLauncher.resolveFileManagerRevealKind")(
465 function* () {
466 const platform = yield* HostProcess.Platform;
467 const env = { ...(yield* readBrowserLaunchEnv), ...(yield* readCommandLookupEnv) };
468 return yield* fileManagerRevealKindForPlatform(platform, env);
469 },
470);
471​
472// Callers apply a timeout (`resolveAvailableEditorsForConfig`) and disconnect
473// mid-connect; neither may cancel a scan other connects are waiting on, or
474// throw away work a slow host (a busy server at startup, a long PATH) needs
475// more than one connect to finish. Expiry uses the monotonic clock
476// (Clock.monotonicTimeNanos), matching the command-resolution cache in
477// @t3tools/shared/shell, so a backward wall-clock adjustment cannot keep an
478// expired entry alive.
479const EDITOR_DISCOVERY_CACHE_TTL_NANOS = 60_000_000_000n;
480​
481interface EditorDiscoveryCacheEntry {
482 readonly scan: Deferred.Deferred<ReadonlyArray<EditorId>>;
483 readonly expiresAtNanos: bigint | undefined;
485​
486export class ExternalLauncher extends Context.Service<
487 ExternalLauncher,
488 {
489 readonly resolveAvailableEditors: () => Effect.Effect<ReadonlyArray<EditorId>>;
490 /**
491 * Only meaningful when `resolveAvailableEditors` includes "file-manager":
492 * on Linux that availability check also carries the directory-handler probe
493 * this capability relies on.
494 */
495 readonly resolveFileManagerRevealKind: () => Effect.Effect<FileManagerRevealKind | undefined>;
496 readonly launchBrowser: (target: string) => Effect.Effect<void, ExternalLauncherError>;
497 readonly launchEditor: (input: LaunchEditorInput) => Effect.Effect<void, ExternalLauncherError>;
498 }
499>()("t3/process/externalLauncher") {}
500​
501const resolveEditorLaunch = Effect.fn("resolveEditorLaunch")(function* (
502 input: LaunchEditorInput,
503): Effect.fn.Return<
504 EditorLaunch,
505 ExternalLauncherError,
506 FileSystem.FileSystem | Path.Path | ChildProcessSpawner.ChildProcessSpawner
507> {
508 const platform = yield* HostProcess.Platform;
509 const env = { ...(yield* readBrowserLaunchEnv), ...(yield* readCommandLookupEnv) };
510 yield* Effect.annotateCurrentSpan({
511 "externalLauncher.editor": input.editor,
512 "externalLauncher.cwd": input.cwd,
513 "externalLauncher.platform": platform,
514 });
515 const editorDef = EDITORS.find((editor) => editor.id === input.editor);
516 if (!editorDef) {
517 return yield* new ExternalLauncherUnknownEditorError({ editor: input.editor });
518 }
519​
520 if (editorDef.commands) {
521 const { command, baseArgs } = Option.getOrElse(
522 yield* resolveEditorCommand(editorDef, env),
523 () => ({
524 command: editorDef.commands[0],
525 baseArgs: "baseArgs" in editorDef ? editorDef.baseArgs : [],
526 }),
527 );
528 return {
529 editor: editorDef.id,
530 target: input.cwd,
531 command,
532 args: [...baseArgs, ...resolveCommandEditorArgs(editorDef, input.cwd)],
533 };
534 }
535​
536 if (editorDef.id !== "file-manager") {
537 return yield* new ExternalLauncherUnsupportedEditorError({ editor: input.editor });
538 }
539​
540 const command = yield* resolveUsableFileManagerCommand(platform, env);
541 if (command === undefined) {
542 return yield* new ExternalLauncherUnsupportedEditorError({ editor: input.editor });
543 }
544​
545 if (input.reveal === true) {
546 return yield* resolveFileManagerRevealLaunch(input.cwd, platform, env, command);
547 }
548​
549 return {
550 editor: editorDef.id,
551 target: input.cwd,
552 command,
553 args:
554 command === "explorer.exe" && env.WSL_DISTRO_NAME !== undefined
555 ? [resolveWslFileManagerPath(input.cwd, env.WSL_DISTRO_NAME)]
556 : [input.cwd],
557 };
558});
559​
560/**
561 * Explorer's contract is the single argument `/select,"<path>"` with only the
562 * path quoted; Node's default spawn quoting wraps the whole argument when the
563 * path has spaces and Explorer misparses it, silently opening a fallback
564 * folder. A single `-ArgumentList` string in Windows PowerShell 5.1 reaches the
565 * child's command line verbatim, preserving the raw switch.
566 */
567function buildFileExplorerRevealPowerShellSource(explorerCommand: string, target: string): string {
568 return `$ProgressPreference = 'SilentlyContinue'; Start-Process ${escapePowerShellStringLiteral(explorerCommand)} -ArgumentList ('/select,"' + ${escapePowerShellStringLiteral(target)} + '"')`;
570​
571function fileExplorerRevealLaunch(
572 target: string,
573 explorerTarget: string,
574 powershellCommand: string,
575): EditorLaunch {
576 return {
577 editor: "file-manager",
578 target,
579 command: powershellCommand,
580 args: [
581 ...POWERSHELL_ARGUMENTS_PREFIX,
582 encodeUtf16LeBase64(buildFileExplorerRevealPowerShellSource("explorer.exe", explorerTarget)),
583 ],
584 };
586​
587function normalizeWindowsFileManagerPath(target: string): string {
588 return target.replaceAll("/", "\\");
590​
591const resolveFileManagerRevealLaunch = Effect.fn("resolveFileManagerRevealLaunch")(function* (
592 target: string,
593 platform: NodeJS.Platform,
594 env: NodeJS.ProcessEnv,
595 command: string,
596): Effect.fn.Return<
597 EditorLaunch,
598 never,
599 FileSystem.FileSystem | Path.Path | ChildProcessSpawner.ChildProcessSpawner
600> {
601 if (platform === "darwin") {
602 return { editor: "file-manager", target, command: "open", args: ["-R", target] };
603 }
604​
605 if (platform === "win32") {
606 return {
607 ...fileExplorerRevealLaunch(
608 target,
609 normalizeWindowsFileManagerPath(target),
610 resolvePowerShellPath(env),
611 ),
612 detached: WINDOWS_POWERSHELL_DETACHED,
613 };
614 }
615​
616 if (
617 command === "explorer.exe" &&
618 shouldUseWindowsHostFromWsl(platform, env) &&
619 env.WSL_DISTRO_NAME !== undefined
620 ) {
621 const explorerTarget = resolveWslFileManagerPath(target, env.WSL_DISTRO_NAME);
622 if (yield* isCommandAvailable(WSL_POWERSHELL_COMMAND, { env })) {
623 // Explorer's raw switch cannot express a double quote, and unlike
624 // Windows paths a WSL path may legally contain one: open the containing
625 // directory in File Explorer instead, matching the advertised
626 // "file-explorer" kind.
627 if (explorerTarget.includes('"')) {
628 const path = yield* Path.Path;
629 return {
630 editor: "file-manager",
631 target,
632 command: "explorer.exe",
633 args: [resolveWslFileManagerPath(path.dirname(target), env.WSL_DISTRO_NAME)],
634 };
635 }
636 return fileExplorerRevealLaunch(target, explorerTarget, WSL_POWERSHELL_COMMAND);
637 }
638 if (hasGraphicalLinuxSession(env) && (yield* isUsableFileManagerCommand("xdg-open", env))) {
639 const path = yield* Path.Path;
640 return { editor: "file-manager", target, command: "xdg-open", args: [path.dirname(target)] };
641 }
642 const path = yield* Path.Path;
643 return {
644 editor: "file-manager",
645 target,
646 command: "explorer.exe",
647 args: [resolveWslFileManagerPath(path.dirname(target), env.WSL_DISTRO_NAME)],
648 };
649 }
650​
651 // Linux file managers have no portable "select this file" flag, so open
652 // the containing directory instead.
653 const path = yield* Path.Path;
654 return { editor: "file-manager", target, command, args: [path.dirname(target)] };
655});
656​
657const launchAndUnref = Effect.fn("externalLauncher.launchAndUnref")(function* (
658 launch: ProcessLaunch,
659 onError: (cause: unknown) => ExternalLauncherError,
660): Effect.fn.Return<void, ExternalLauncherError, ChildProcessSpawner.ChildProcessSpawner> {
661 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
662 const command = ChildProcess.make(launch.command, launch.args, launch.options);
663​
664 yield* spawner.spawn(command).pipe(
665 Effect.flatMap((handle) => handle.unref),
666 Effect.asVoid,
667 Effect.scoped,
668 Effect.mapError(onError),
669 );
670});
671​
672const launchBrowser = Effect.fn("externalLauncher.launchBrowser")(function* (
673 target: string,
674): Effect.fn.Return<void, ExternalLauncherError, ChildProcessSpawner.ChildProcessSpawner> {
675 const launch = yield* resolveBrowserLaunch(target);
676 return yield* launchAndUnref(
677 launch,
678 (cause) =>
679 new ExternalLauncherBrowserSpawnError({
680 target,
681 command: launch.command,
682 args: launch.args,
683 cause,
684 }),
685 );
686});
687​
688const launchEditorProcess = Effect.fn("externalLauncher.launchEditorProcess")(function* (
689 launch: EditorLaunch,
690): Effect.fn.Return<
691 void,
692 ExternalLauncherError,
693 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
694> {
695 const env = yield* readCommandLookupEnv;
696 if (!(yield* isCommandAvailable(launch.command, { env }))) {
697 return yield* new ExternalLauncherCommandNotFoundError({
698 editor: launch.editor,
699 command: launch.command,
700 });
701 }
702​
703 const spawnCommand = yield* resolveSpawnCommand(launch.command, launch.args, { env });
704 if (spawnCommand.shell && launch.args.some((arg) => WINDOWS_SHIM_UNSAFE_ARG_PATTERN.test(arg))) {
705 return yield* new ExternalLauncherUnsupportedTargetError({ editor: launch.editor });
706 }
707 yield* launchAndUnref(
708 {
709 command: spawnCommand.command,
710 args: spawnCommand.args,
711 options: {
712 detached: launch.detached ?? true,
713 shell: spawnCommand.shell,
714 stdin: "ignore",
715 stdout: "ignore",
716 stderr: "ignore",
717 },
718 },
719 (cause) =>
720 new ExternalLauncherEditorSpawnError({
721 editor: launch.editor,
722 target: launch.target,
723 command: spawnCommand.command,
724 args: spawnCommand.args,
725 cause,
726 }),
727 );
728});
729​
730/** @public Service construction is part of the canonical Effect module API. */
731export const make = Effect.gen(function* () {
732 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
733 const fileSystem = yield* FileSystem.FileSystem;
734 const path = yield* Path.Path;
735​
736 const provideCommandResolutionServices = <A, E, R>(
737 effect: Effect.Effect<A, E, R | FileSystem.FileSystem | Path.Path>,
738 ) =>
739 effect.pipe(
740 Effect.provideService(FileSystem.FileSystem, fileSystem),
741 Effect.provideService(Path.Path, path),
742 );
743​
744 const scope = yield* Scope.Scope;
745 const editorDiscoveryCache = yield* Ref.make<Option.Option<EditorDiscoveryCacheEntry>>(
746 Option.none(),
747 );
748 const runEditorDiscovery = (scan: Deferred.Deferred<ReadonlyArray<EditorId>>) =>
749 provideCommandResolutionServices(resolveAvailableEditors()).pipe(
750 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
751 Effect.onExit((exit) =>
752 Effect.gen(function* () {
753 const expiresAtNanos =
754 (yield* Clock.monotonicTimeNanos) + EDITOR_DISCOVERY_CACHE_TTL_NANOS;
755 yield* Ref.update(editorDiscoveryCache, (current) =>
756 Option.isNone(current) || current.value.scan !== scan
757 ? current
758 : Exit.isSuccess(exit)
759 ? Option.some({ scan, expiresAtNanos })
760 : Option.none(),
761 );
762 yield* Deferred.done(scan, exit);
763 }),
764 ),
765 Effect.interruptible,
766 Effect.forkIn(scope),
767 );
768 // Claiming the cache entry and starting its scan must not be split by an
769 // interrupt, or the entry would wait on a scan that never runs.
770 const acquireEditorDiscovery = Effect.gen(function* () {
771 const nowNanos = yield* Clock.monotonicTimeNanos;
772 const [scan, isNewScan] = yield* Ref.modify(
773 editorDiscoveryCache,
774 (
775 current,
776 ): [
777 [EditorDiscoveryCacheEntry["scan"], boolean],
778 Option.Option<EditorDiscoveryCacheEntry>,
779 ] => {
780 if (
781 Option.isSome(current) &&
782 (current.value.expiresAtNanos === undefined || current.value.expiresAtNanos > nowNanos)
783 ) {
784 return [[current.value.scan, false], current];
785 }
786 const scan = Deferred.makeUnsafe<ReadonlyArray<EditorId>>();
787 return [[scan, true], Option.some({ scan, expiresAtNanos: undefined })];
788 },
789 );
790 if (isNewScan) {
791 yield* runEditorDiscovery(scan);
792 }
793 return scan;
794 }).pipe(Effect.uninterruptible);
795 const cachedAvailableEditors = Effect.flatMap(acquireEditorDiscovery, Deferred.await);
796​
797 return ExternalLauncher.of({
798 resolveAvailableEditors: () => cachedAvailableEditors,
799 resolveFileManagerRevealKind: () =>
800 provideCommandResolutionServices(resolveFileManagerRevealKind()).pipe(
801 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
802 ),
803 launchBrowser: (target) =>
804 launchBrowser(target).pipe(
805 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
806 ),
807 launchEditor: (input) =>
808 provideCommandResolutionServices(
809 Effect.flatMap(resolveEditorLaunch(input), launchEditorProcess),
810 ).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner)),
811 });
812});
813​
814export const layer = Layer.effect(ExternalLauncher, make);