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 (
44 (editorId === "cursor" || editorId === "vscode") && LINE_COLUMN_SUFFIX_PATTERN.test(target)
45 );
46}
47
48function fileManagerCommandForPlatform(platform: NodeJS.Platform): string {
49 switch (platform) {
50 case "darwin":
51 return "open";
52 case "win32":
53 return "explorer";
54 default:
55 return "xdg-open";
56 }
57}
58
59function stripWrappingQuotes(value: string): string {
60 return value.replace(/^"+|"+$/g, "");
61}
62
63function resolvePathEnvironmentVariable(env: NodeJS.ProcessEnv): string {
64 return env.PATH ?? env.Path ?? env.path ?? "";
65}
66
67function resolveWindowsPathExtensions(env: NodeJS.ProcessEnv): ReadonlyArray<string> {
68 const rawValue = env.PATHEXT;
69 const fallback = [".COM", ".EXE", ".BAT", ".CMD"];
70 if (!rawValue) return fallback;
71
72 const parsed = rawValue
73 .split(";")
74 .map((entry) => entry.trim())
75 .filter((entry) => entry.length > 0)
76 .map((entry) => (entry.startsWith(".") ? entry.toUpperCase() : `.${entry.toUpperCase()}`));
77 return parsed.length > 0 ? Array.from(new Set(parsed)) : fallback;
78}
79
80function resolveCommandCandidates(
81 command: string,
82 platform: NodeJS.Platform,
83 windowsPathExtensions: ReadonlyArray<string>,
84): ReadonlyArray<string> {
85 if (platform !== "win32") return [command];
86 const extension = extname(command);
87 const normalizedExtension = extension.toUpperCase();
88
89 if (extension.length > 0 && windowsPathExtensions.includes(normalizedExtension)) {
90 const commandWithoutExtension = command.slice(0, -extension.length);
91 return Array.from(
92 new Set([
93 command,
94 `${commandWithoutExtension}${normalizedExtension}`,
95 `${commandWithoutExtension}${normalizedExtension.toLowerCase()}`,
96 ]),
97 );
98 }
99
100 const candidates: string[] = [];
101 for (const extension of windowsPathExtensions) {
102 candidates.push(`${command}${extension}`);
103 candidates.push(`${command}${extension.toLowerCase()}`);
104 }
105 return Array.from(new Set(candidates));
106}
107
108function isExecutableFile(
109 filePath: string,
110 platform: NodeJS.Platform,
111 windowsPathExtensions: ReadonlyArray<string>,
112): boolean {
113 try {
114 const stat = statSync(filePath);
115 if (!stat.isFile()) return false;
116 if (platform === "win32") {
117 const extension = extname(filePath);
118 if (extension.length === 0) return false;
119 return windowsPathExtensions.includes(extension.toUpperCase());
120 }
121 accessSync(filePath, constants.X_OK);
122 return true;
123 } catch {
124 return false;
125 }
126}
127
128function resolvePathDelimiter(platform: NodeJS.Platform): string {
129 return platform === "win32" ? ";" : ":";
130}
131
132export function isCommandAvailable(
133 command: string,
134 options: CommandAvailabilityOptions = {},
135): boolean {
136 const platform = options.platform ?? process.platform;
137 const env = options.env ?? process.env;
138 const windowsPathExtensions = platform === "win32" ? resolveWindowsPathExtensions(env) : [];
139 const commandCandidates = resolveCommandCandidates(command, platform, windowsPathExtensions);
140
141 if (command.includes("/") || command.includes("\\")) {
142 return commandCandidates.some((candidate) =>
143 isExecutableFile(candidate, platform, windowsPathExtensions),
144 );
145 }
146
147 const pathValue = resolvePathEnvironmentVariable(env);
148 if (pathValue.length === 0) return false;
149 const pathEntries = pathValue
150 .split(resolvePathDelimiter(platform))
151 .map((entry) => stripWrappingQuotes(entry.trim()))
152 .filter((entry) => entry.length > 0);
153
154 for (const pathEntry of pathEntries) {
155 for (const candidate of commandCandidates) {
156 if (isExecutableFile(join(pathEntry, candidate), platform, windowsPathExtensions)) {
157 return true;
158 }
159 }
160 }
161 return false;
162}
163
164export function resolveAvailableEditors(
165 platform: NodeJS.Platform = process.platform,
166 env: NodeJS.ProcessEnv = process.env,
167): ReadonlyArray<EditorId> {
168 const available: EditorId[] = [];
169
170 for (const editor of EDITORS) {
171 const command = editor.command ?? fileManagerCommandForPlatform(platform);
172 if (isCommandAvailable(command, { platform, env })) {
173 available.push(editor.id);
174 }
175 }
176
177 return available;
178}
179
180/**
181 * OpenShape - Service API for browser and editor launch actions.
182 */
183export interface OpenShape {
184 /**
185 * Open a URL target in the default browser.
186 */
187 readonly openBrowser: (target: string) => Effect.Effect<void, OpenError>;
188
189 /**
190 * Open a workspace path in a selected editor integration.
191 *
192 * Launches the editor as a detached process so server startup is not blocked.
193 */
194 readonly openInEditor: (input: OpenInEditorInput) => Effect.Effect<void, OpenError>;
195}
196
197/**
198 * Open - Service tag for browser/editor launch operations.
199 */
200export class Open extends ServiceMap.Service<Open, OpenShape>()("t3/open") {}
201
202// ==============================
203// Implementations
204// ==============================
205
206export const resolveEditorLaunch = Effect.fnUntraced(function* (
207 input: OpenInEditorInput,
208 platform: NodeJS.Platform = process.platform,
209): Effect.fn.Return<EditorLaunch, OpenError> {
210 const editorDef = EDITORS.find((editor) => editor.id === input.editor);
211 if (!editorDef) {
212 return yield* new OpenError({ message: `Unknown editor: ${input.editor}` });
213 }
214
215 if (editorDef.command) {
216 return shouldUseGotoFlag(editorDef.id, input.cwd)
217 ? { command: editorDef.command, args: ["--goto", input.cwd] }
218 : { command: editorDef.command, args: [input.cwd] };
219 }
220
221 if (editorDef.id !== "file-manager") {
222 return yield* new OpenError({ message: `Unsupported editor: ${input.editor}` });
223 }
224
225 return { command: fileManagerCommandForPlatform(platform), args: [input.cwd] };
226});
227
228export const launchDetached = (launch: EditorLaunch) =>
229 Effect.gen(function* () {
230 if (!isCommandAvailable(launch.command)) {
231 return yield* new OpenError({ message: `Editor command not found: ${launch.command}` });
232 }
233
234 yield* Effect.callback<void, OpenError>((resume) => {
235 let child;
236 try {
237 child = spawn(launch.command, [...launch.args], {
238 detached: true,
239 stdio: "ignore",
240 shell: process.platform === "win32",
241 });
242 } catch (error) {
243 return resume(
244 Effect.fail(new OpenError({ message: "failed to spawn detached process", cause: error })),
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);