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

externalLauncher.ts

463 lines13.9 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 type EditorId,
18 type LaunchEditorInput,
19} from "@v12/contracts";
20import { HostProcessPlatform } from "@v12/shared/hostProcess";
21import { isCommandAvailable, resolveSpawnCommand } from "@v12/shared/shell";
22import * as Config from "effect/Config";
23import * as Context from "effect/Context";
24import * as Effect from "effect/Effect";
25import * as Encoding from "effect/Encoding";
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 ChildProcess from "effect/unstable/process/ChildProcess";
31import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
32​
33// ==============================
34// Definitions
35// ==============================
36​
37export {
38 ExternalLauncherError,
39 ExternalLauncherBrowserSpawnError,
40 ExternalLauncherCommandNotFoundError,
41 ExternalLauncherEditorSpawnError,
42 ExternalLauncherUnknownEditorError,
43 ExternalLauncherUnsupportedEditorError,
44 isExternalLauncherError,
45} from "@v12/contracts";
46export type { LaunchEditorInput };
47interface EditorLaunch {
48 readonly editor: EditorId;
49 readonly target: string;
50 readonly command: string;
51 readonly args: ReadonlyArray<string>;
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​
66const TARGET_WITH_POSITION_PATTERN = /^(.*?):(\d+)(?::(\d+))?$/;
67const POWERSHELL_ARGUMENTS_PREFIX = [
68 "-NoProfile",
69 "-NonInteractive",
70 "-ExecutionPolicy",
71 "Bypass",
72 "-EncodedCommand",
73] as const;
74​
75const DETACHED_IGNORE_STDIO_OPTIONS = {
76 detached: true,
77 stdin: "ignore",
78 stdout: "ignore",
79 stderr: "ignore",
80} as const satisfies ChildProcess.CommandOptions;
81​
82const compactEnv = (input: Record<string, Option.Option<string>>): NodeJS.ProcessEnv =>
83 Object.fromEntries(
84 Object.entries(input).flatMap(([key, value]) =>
85 Option.match(value, {
86 onNone: () => [],
87 onSome: (resolved) => [[key, resolved]],
88 }),
89 ),
90 );
91​
92const BrowserLaunchEnvConfig = Config.all({
93 SYSTEMROOT: Config.string("SYSTEMROOT").pipe(Config.option),
94 windir: Config.string("windir").pipe(Config.option),
95 WSL_DISTRO_NAME: Config.string("WSL_DISTRO_NAME").pipe(Config.option),
96 WSL_INTEROP: Config.string("WSL_INTEROP").pipe(Config.option),
97 SSH_CONNECTION: Config.string("SSH_CONNECTION").pipe(Config.option),
98 SSH_TTY: Config.string("SSH_TTY").pipe(Config.option),
99 container: Config.string("container").pipe(Config.option),
100}).pipe(Config.map(compactEnv));
101​
102const CommandLookupEnvConfig = Config.all({
103 PATH: Config.string("PATH").pipe(Config.option),
104 Path: Config.string("Path").pipe(Config.option),
105 path: Config.string("path").pipe(Config.option),
106 PATHEXT: Config.string("PATHEXT").pipe(Config.option),
107}).pipe(Config.map(compactEnv));
108​
109const readBrowserLaunchEnv = BrowserLaunchEnvConfig.pipe(Effect.orElseSucceed(() => ({})));
110const readCommandLookupEnv = CommandLookupEnvConfig.pipe(Effect.orElseSucceed(() => ({})));
111​
112function parseTargetPathAndPosition(target: string): Option.Option<TargetPathAndPosition> {
113 const match = TARGET_WITH_POSITION_PATTERN.exec(target);
114 if (!match?.[1] || !match[2]) {
115 return Option.none();
116 }
117​
118 return Option.some({
119 path: match[1],
120 line: match[2],
121 column: Option.fromUndefinedOr(match[3]),
122 });
124​
125function resolveCommandEditorArgs(
126 editor: (typeof EDITORS)[number],
127 target: string,
128): ReadonlyArray<string> {
129 const parsedTarget = parseTargetPathAndPosition(target);
130​
131 switch (editor.launchStyle) {
132 case "direct-path":
133 return [target];
134 case "goto":
135 return Option.isSome(parsedTarget) ? ["--goto", target] : [target];
136 case "line-column":
137 return Option.match(parsedTarget, {
138 onNone: () => [target],
139 onSome: ({ path, line, column }) => [
140 "--line",
141 line,
142 ...Option.match(column, {
143 onNone: () => [],
144 onSome: (value) => ["--column", value],
145 }),
146 path,
147 ],
148 });
149 }
151​
152function resolveEditorArgs(
153 editor: (typeof EDITORS)[number],
154 target: string,
155): ReadonlyArray<string> {
156 const baseArgs = "baseArgs" in editor ? editor.baseArgs : [];
157 return [...baseArgs, ...resolveCommandEditorArgs(editor, target)];
159​
160const resolveAvailableCommand = Effect.fn("externalLauncher.resolveAvailableCommand")(function* (
161 commands: ReadonlyArray<string>,
162 env: NodeJS.ProcessEnv,
163): Effect.fn.Return<Option.Option<string>, never, FileSystem.FileSystem | Path.Path> {
164 for (const command of commands) {
165 if (yield* isCommandAvailable(command, { env })) {
166 return Option.some(command);
167 }
168 }
169 return Option.none();
170});
171​
172function encodeUtf16LeBase64(input: string): string {
173 const bytes = new Uint8Array(input.length * 2);
174 for (let index = 0; index < input.length; index += 1) {
175 const code = input.charCodeAt(index);
176 bytes[index * 2] = code & 0xff;
177 bytes[index * 2 + 1] = code >>> 8;
178 }
179 return Encoding.encodeBase64(bytes);
181​
182function escapePowerShellStringLiteral(input: string): string {
183 return `'${input.replaceAll("'", "''")}'`;
185​
186function resolvePowerShellPath(env: NodeJS.ProcessEnv = {}): string {
187 return `${env.SYSTEMROOT || env.windir || String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;
189​
190function resolveWslPowerShellPath(): string {
191 return "/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe";
193​
194function shouldUseWindowsBrowserFromWsl(
195 platform: NodeJS.Platform,
196 env: NodeJS.ProcessEnv = {},
197): boolean {
198 return (
199 platform === "linux" &&
200 (env.WSL_DISTRO_NAME !== undefined || env.WSL_INTEROP !== undefined) &&
201 env.SSH_CONNECTION === undefined &&
202 env.SSH_TTY === undefined &&
203 env.container === undefined
204 );
206​
207function resolveWindowsBrowserLaunch(target: string, command: string): ProcessLaunch {
208 const encodedCommand = encodeUtf16LeBase64(
209 `$ProgressPreference = 'SilentlyContinue'; Start ${escapePowerShellStringLiteral(target)}`,
210 );
211 return {
212 command,
213 args: [...POWERSHELL_ARGUMENTS_PREFIX, encodedCommand],
214 options: {
215 detached: true,
216 shell: false,
217 stdin: "ignore",
218 stdout: "ignore",
219 stderr: "ignore",
220 },
221 };
223​
224function fileManagerCommandForPlatform(platform: NodeJS.Platform): string {
225 switch (platform) {
226 case "darwin":
227 return "open";
228 case "win32":
229 return "explorer";
230 default:
231 return "xdg-open";
232 }
234​
235function buildBrowserLaunch(
236 target: string,
237 platform: NodeJS.Platform,
238 env: NodeJS.ProcessEnv = {},
239): ProcessLaunch {
240 if (platform === "darwin") {
241 return {
242 command: "open",
243 args: [target],
244 options: DETACHED_IGNORE_STDIO_OPTIONS,
245 };
246 }
247​
248 if (platform === "win32") {
249 return resolveWindowsBrowserLaunch(target, resolvePowerShellPath(env));
250 }
251​
252 if (shouldUseWindowsBrowserFromWsl(platform, env)) {
253 return resolveWindowsBrowserLaunch(target, resolveWslPowerShellPath());
254 }
255​
256 return {
257 command: "xdg-open",
258 args: [target],
259 options: DETACHED_IGNORE_STDIO_OPTIONS,
260 };
262​
263const buildAvailableEditors = Effect.fn("externalLauncher.buildAvailableEditors")(function* (
264 platform: NodeJS.Platform,
265 env: NodeJS.ProcessEnv,
266): Effect.fn.Return<ReadonlyArray<EditorId>, never, FileSystem.FileSystem | Path.Path> {
267 const available: EditorId[] = [];
268​
269 for (const editor of EDITORS) {
270 if (editor.commands === null) {
271 const command = fileManagerCommandForPlatform(platform);
272 if (yield* isCommandAvailable(command, { env })) {
273 available.push(editor.id);
274 }
275 continue;
276 }
277​
278 const command = yield* resolveAvailableCommand(editor.commands, env);
279 if (Option.isSome(command)) {
280 available.push(editor.id);
281 }
282 }
283​
284 return available;
285});
286​
287const resolveBrowserLaunch = Effect.fn("externalLauncher.resolveBrowserLaunch")(function* (
288 target: string,
289) {
290 const platform = yield* HostProcessPlatform;
291 const env = yield* readBrowserLaunchEnv;
292 return buildBrowserLaunch(target, platform, env);
293});
294​
295const resolveAvailableEditors = Effect.fn("externalLauncher.resolveAvailableEditors")(function* () {
296 const platform = yield* HostProcessPlatform;
297 const env = yield* readCommandLookupEnv;
298 return yield* buildAvailableEditors(platform, env);
299});
300​
301/**
302 * ExternalLauncher - Service tag for browser/editor launch operations.
303 */
304export class ExternalLauncher extends Context.Service<
305 ExternalLauncher,
306 {
307 readonly resolveAvailableEditors: () => Effect.Effect<ReadonlyArray<EditorId>>;
308 /** Launch a URL target in the default browser. */
309 readonly launchBrowser: (target: string) => Effect.Effect<void, ExternalLauncherError>;
310 /**
311 * Launch a workspace path in a selected editor integration.
312 *
313 * Launches the editor as a detached process so server startup is not blocked.
314 */
315 readonly launchEditor: (input: LaunchEditorInput) => Effect.Effect<void, ExternalLauncherError>;
316 }
317>()("v12/process/externalLauncher") {}
318​
319// ==============================
320// Implementations
321// ==============================
322​
323const resolveEditorLaunch = Effect.fn("resolveEditorLaunch")(function* (
324 input: LaunchEditorInput,
325): Effect.fn.Return<EditorLaunch, ExternalLauncherError, FileSystem.FileSystem | Path.Path> {
326 const platform = yield* HostProcessPlatform;
327 const env = yield* readCommandLookupEnv;
328 yield* Effect.annotateCurrentSpan({
329 "externalLauncher.editor": input.editor,
330 "externalLauncher.cwd": input.cwd,
331 "externalLauncher.platform": platform,
332 });
333 const editorDef = EDITORS.find((editor) => editor.id === input.editor);
334 if (!editorDef) {
335 return yield* new ExternalLauncherUnknownEditorError({ editor: input.editor });
336 }
337​
338 if (editorDef.commands) {
339 const command = Option.getOrElse(
340 yield* resolveAvailableCommand(editorDef.commands, env),
341 () => editorDef.commands[0],
342 );
343 return {
344 editor: editorDef.id,
345 target: input.cwd,
346 command,
347 args: resolveEditorArgs(editorDef, input.cwd),
348 };
349 }
350​
351 if (editorDef.id !== "file-manager") {
352 return yield* new ExternalLauncherUnsupportedEditorError({ editor: input.editor });
353 }
354​
355 return {
356 editor: editorDef.id,
357 target: input.cwd,
358 command: fileManagerCommandForPlatform(platform),
359 args: [input.cwd],
360 };
361});
362​
363const launchAndUnref = Effect.fn("externalLauncher.launchAndUnref")(function* (
364 launch: ProcessLaunch,
365 onError: (cause: unknown) => ExternalLauncherError,
366): Effect.fn.Return<void, ExternalLauncherError, ChildProcessSpawner.ChildProcessSpawner> {
367 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
368 const command = ChildProcess.make(launch.command, launch.args, launch.options);
369​
370 yield* spawner.spawn(command).pipe(
371 Effect.flatMap((handle) => handle.unref),
372 Effect.asVoid,
373 Effect.scoped,
374 Effect.mapError(onError),
375 );
376});
377​
378const launchBrowser = Effect.fn("externalLauncher.launchBrowser")(function* (
379 target: string,
380): Effect.fn.Return<void, ExternalLauncherError, ChildProcessSpawner.ChildProcessSpawner> {
381 const launch = yield* resolveBrowserLaunch(target);
382 return yield* launchAndUnref(
383 launch,
384 (cause) =>
385 new ExternalLauncherBrowserSpawnError({
386 target,
387 command: launch.command,
388 args: launch.args,
389 cause,
390 }),
391 );
392});
393​
394const launchEditorProcess = Effect.fn("externalLauncher.launchEditorProcess")(function* (
395 launch: EditorLaunch,
396): Effect.fn.Return<
397 void,
398 ExternalLauncherError,
399 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
400> {
401 const env = yield* readCommandLookupEnv;
402 if (!(yield* isCommandAvailable(launch.command, { env }))) {
403 return yield* new ExternalLauncherCommandNotFoundError({
404 editor: launch.editor,
405 command: launch.command,
406 });
407 }
408​
409 const spawnCommand = yield* resolveSpawnCommand(launch.command, launch.args, { env });
410 yield* launchAndUnref(
411 {
412 command: spawnCommand.command,
413 args: spawnCommand.args,
414 options: {
415 detached: true,
416 shell: spawnCommand.shell,
417 stdin: "ignore",
418 stdout: "ignore",
419 stderr: "ignore",
420 },
421 },
422 (cause) =>
423 new ExternalLauncherEditorSpawnError({
424 editor: launch.editor,
425 target: launch.target,
426 command: spawnCommand.command,
427 args: spawnCommand.args,
428 cause,
429 }),
430 );
431});
432​
433export const make = Effect.gen(function* () {
434 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
435 const fileSystem = yield* FileSystem.FileSystem;
436 const path = yield* Path.Path;
437​
438 const provideCommandResolutionServices = <A, E, R>(
439 effect: Effect.Effect<A, E, R | FileSystem.FileSystem | Path.Path>,
440 ) =>
441 effect.pipe(
442 Effect.provideService(FileSystem.FileSystem, fileSystem),
443 Effect.provideService(Path.Path, path),
444 );
445​
446 return ExternalLauncher.of({
447 resolveAvailableEditors: () => provideCommandResolutionServices(resolveAvailableEditors()),
448 launchBrowser: (target) =>
449 launchBrowser(target).pipe(
450 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
451 ),
452 launchEditor: (input) =>
453 provideCommandResolutionServices(
454 Effect.flatMap(resolveEditorLaunch(input), (launch) =>
455 launchEditorProcess(launch).pipe(
456 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
457 ),
458 ),
459 ),
460 });
461});
462​
463export const layer = Layer.effect(ExternalLauncher, make);