Open History to see the last commit
1/**
2 * Open - Browser/editor launch service interface.
3 *
4 * Owns process launch helpers for opening URLs in a browser and workspace
5 * paths in a configured editor.
6 *
7 * @module Open
8 */
9import { spawn } from "node:child_process";
10import { accessSync, constants, statSync } from "node:fs";
11import { extname, join } from "node:path";
12
13import { EDITORS, type EditorId } from "@t3tools/contracts";
14import { ServiceMap, Schema, Effect, Layer } from "effect";
15
16// ==============================
17// Definitions
18// ==============================
19
20export class OpenError extends Schema.TaggedErrorClass<OpenError>()("OpenError", {
21 message: Schema.String,
22 cause: Schema.optional(Schema.Defect),
23}) {}
24
25export interface OpenInEditorInput {
26 readonly cwd: string;
27 readonly editor: EditorId;
28}
29
30interface EditorLaunch {
31 readonly command: string;
32 readonly args: ReadonlyArray<string>;
33}
34
35interface CommandAvailabilityOptions {
36 readonly platform?: NodeJS.Platform;
37 readonly env?: NodeJS.ProcessEnv;
38}
39
40const LINE_COLUMN_SUFFIX_PATTERN = /:\d+(?::\d+)?$/;
41
42function shouldUseGotoFlag(editorId: EditorId, target: string): boolean {
43 return (editorId === "cursor" || editorId === "vscode") && LINE_COLUMN_SUFFIX_PATTERN.test(target);
44}
45
46function fileManagerCommandForPlatform(platform: NodeJS.Platform): string {
47 switch (platform) {
48 case "darwin":
49 return "open";
50 case "win32":
51 return "explorer";
52 default:
53 return "xdg-open";
54 }
55}
56
57function stripWrappingQuotes(value: string): string {
58 return value.replace(/^"+|"+$/g, "");
59}
60
61function resolvePathEnvironmentVariable(env: NodeJS.ProcessEnv): string {
62 return env.PATH ?? env.Path ?? env.path ?? "";
63}
64
65function resolveWindowsPathExtensions(env: NodeJS.ProcessEnv): ReadonlyArray<string> {
66 const rawValue = env.PATHEXT;
67 const fallback = [".COM", ".EXE", ".BAT", ".CMD"];
68 if (!rawValue) return fallback;
69
70 const parsed = rawValue
71 .split(";")
72 .map((entry) => entry.trim())
73 .filter((entry) => entry.length > 0)
74 .map((entry) => (entry.startsWith(".") ? entry.toUpperCase() : `.${entry.toUpperCase()}`));
75 return parsed.length > 0 ? Array.from(new Set(parsed)) : fallback;
76}
77
78function resolveCommandCandidates(
79 command: string,
80 platform: NodeJS.Platform,
81 windowsPathExtensions: ReadonlyArray<string>,
82): ReadonlyArray<string> {
83 if (platform !== "win32") return [command];
84 const extension = extname(command);
85 const normalizedExtension = extension.toUpperCase();
86
87 if (extension.length > 0 && windowsPathExtensions.includes(normalizedExtension)) {
88 const commandWithoutExtension = command.slice(0, -extension.length);
89 return Array.from(
90 new Set([
91 command,
92 `${commandWithoutExtension}${normalizedExtension}`,
93 `${commandWithoutExtension}${normalizedExtension.toLowerCase()}`,
94 ]),
95 );
96 }
97
98 const candidates: string[] = [];
99 for (const extension of windowsPathExtensions) {
100 candidates.push(`${command}${extension}`);
101 candidates.push(`${command}${extension.toLowerCase()}`);
102 }
103 return Array.from(new Set(candidates));
104}
105
106function isExecutableFile(
107 filePath: string,
108 platform: NodeJS.Platform,
109 windowsPathExtensions: ReadonlyArray<string>,
110): boolean {
111 try {
112 const stat = statSync(filePath);
113 if (!stat.isFile()) return false;
114 if (platform === "win32") {
115 const extension = extname(filePath);
116 if (extension.length === 0) return false;
117 return windowsPathExtensions.includes(extension.toUpperCase());
118 }
119 accessSync(filePath, constants.X_OK);
120 return true;
121 } catch {
122 return false;
123 }
124}
125
126function resolvePathDelimiter(platform: NodeJS.Platform): string {
127 return platform === "win32" ? ";" : ":";
128}
129
130export function isCommandAvailable(
131 command: string,
132 options: CommandAvailabilityOptions = {},
133): boolean {
134 const platform = options.platform ?? process.platform;
135 const env = options.env ?? process.env;
136 const windowsPathExtensions = platform === "win32" ? resolveWindowsPathExtensions(env) : [];
137 const commandCandidates = resolveCommandCandidates(command, platform, windowsPathExtensions);
138
139 if (command.includes("/") || command.includes("\\")) {
140 return commandCandidates.some((candidate) =>
141 isExecutableFile(candidate, platform, windowsPathExtensions),
142 );
143 }
144
145 const pathValue = resolvePathEnvironmentVariable(env);
146 if (pathValue.length === 0) return false;
147 const pathEntries = pathValue
148 .split(resolvePathDelimiter(platform))
149 .map((entry) => stripWrappingQuotes(entry.trim()))
150 .filter((entry) => entry.length > 0);
151
152 for (const pathEntry of pathEntries) {
153 for (const candidate of commandCandidates) {
154 if (isExecutableFile(join(pathEntry, candidate), platform, windowsPathExtensions)) {
155 return true;
156 }
157 }
158 }
159 return false;
160}
161
162export function resolveAvailableEditors(
163 platform: NodeJS.Platform = process.platform,
164 env: NodeJS.ProcessEnv = process.env,
165): ReadonlyArray<EditorId> {
166 const available: EditorId[] = [];
167
168 for (const editor of EDITORS) {
169 const command = editor.command ?? fileManagerCommandForPlatform(platform);
170 if (isCommandAvailable(command, { platform, env })) {
171 available.push(editor.id);
172 }
173 }
174
175 return available;
176}
177
178/**
179 * OpenShape - Service API for browser and editor launch actions.
180 */
181export interface OpenShape {
182 /**
183 * Open a URL target in the default browser.
184 */
185 readonly openBrowser: (target: string) => Effect.Effect<void, OpenError>;
186
187 /**
188 * Open a workspace path in a selected editor integration.
189 *
190 * Launches the editor as a detached process so server startup is not blocked.
191 */
192 readonly openInEditor: (input: OpenInEditorInput) => Effect.Effect<void, OpenError>;
193}
194
195/**
196 * Open - Service tag for browser/editor launch operations.
197 */
198export class Open extends ServiceMap.Service<Open, OpenShape>()("t3/open") {}
199
200// ==============================
201// Implementations
202// ==============================
203
204export const resolveEditorLaunch = Effect.fnUntraced(function* (
205 input: OpenInEditorInput,
206 platform: NodeJS.Platform = process.platform,
207): Effect.fn.Return<EditorLaunch, OpenError> {
208 const editorDef = EDITORS.find((editor) => editor.id === input.editor);
209 if (!editorDef) {
210 return yield* new OpenError({ message: `Unknown editor: ${input.editor}` });
211 }
212
213 if (editorDef.command) {
214 return shouldUseGotoFlag(editorDef.id, input.cwd)
215 ? { command: editorDef.command, args: ["--goto", input.cwd] }
216 : { command: editorDef.command, args: [input.cwd] };
217 }
218
219 if (editorDef.id !== "file-manager") {
220 return yield* new OpenError({ message: `Unsupported editor: ${input.editor}` });
221 }
222
223 return { command: fileManagerCommandForPlatform(platform), args: [input.cwd] };
224});
225
226export const launchDetached = (launch: EditorLaunch) =>
227 Effect.gen(function* () {
228 if (!isCommandAvailable(launch.command)) {
229 return yield* new OpenError({ message: `Editor command not found: ${launch.command}` });
230 }
231
232 yield* Effect.callback<void, OpenError>((resume) => {
233 let child;
234 try {
235 child = spawn(launch.command, [...launch.args], {
236 detached: true,
237 stdio: "ignore",
238 shell: process.platform === "win32",
239 });
240 } catch (error) {
241 return resume(
242 Effect.fail(
243 new OpenError({ message: "failed to spawn detached process", cause: error }),
244 ),
245 );
246 }
247
248 const handleSpawn = () => {
249 child.unref();
250 resume(Effect.void);
251 };
252
253 child.once("spawn", handleSpawn);
254 child.once("error", (cause) =>
255 resume(Effect.fail(new OpenError({ message: "failed to spawn detached process", cause }))),
256 );
257 });
258 });
259
260const make = Effect.gen(function* () {
261 const open = yield* Effect.tryPromise({
262 try: () => import("open"),
263 catch: (cause) => new OpenError({ message: "failed to load browser opener", cause }),
264 });
265
266 return {
267 openBrowser: (target) =>
268 Effect.tryPromise({
269 try: () => open.default(target),
270 catch: (cause) => new OpenError({ message: "Browser auto-open failed", cause }),
271 }),
272 openInEditor: (input) => Effect.flatMap(resolveEditorLaunch(input), launchDetached),
273 } satisfies OpenShape;
274});
275
276export const OpenLive = Layer.effect(Open, make);