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

externalLauncher.ts

849 lines29.2 KB

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