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

editor.ts

361 lines11.3 KB

1import * as Schema from "effect/Schema";
2import { PositiveInt, TrimmedNonEmptyString } from "./baseSchemas.ts";
3​
4export const EditorLaunchStyle = Schema.Literals(["direct-path", "goto", "line-column"]);
5export type EditorLaunchStyle = typeof EditorLaunchStyle.Type;
6​
7type EditorDefinition = {
8 readonly id: string;
9 readonly label: string;
10 readonly commands: readonly [string, ...string[]] | null;
11 readonly baseArgs?: readonly string[];
12 readonly launchStyle: EditorLaunchStyle;
13 readonly remoteScheme?: string;
14 readonly jetbrainsProductCode?: string;
15};
16​
17export const EDITORS = [
18 {
19 id: "cursor",
20 label: "Cursor",
21 commands: ["cursor"],
22 // File and workspace opens must target the IDE even when the Agents Window is active.
23 baseArgs: ["--classic"],
24 launchStyle: "goto",
25 remoteScheme: "cursor",
26 },
27 { id: "trae", label: "Trae", commands: ["trae"], launchStyle: "goto" },
28 { id: "kiro", label: "Kiro", commands: ["kiro"], baseArgs: ["ide"], launchStyle: "goto" },
29 {
30 id: "vscode",
31 label: "VS Code",
32 commands: ["code"],
33 launchStyle: "goto",
34 remoteScheme: "vscode",
35 },
36 {
37 id: "vscode-insiders",
38 label: "VS Code Insiders",
39 commands: ["code-insiders"],
40 launchStyle: "goto",
41 remoteScheme: "vscode-insiders",
42 },
43 {
44 id: "vscodium",
45 label: "VSCodium",
46 commands: ["codium"],
47 launchStyle: "goto",
48 remoteScheme: "vscodium",
49 },
50 {
51 id: "zed",
52 label: "Zed",
53 commands: ["zed", "zeditor"],
54 launchStyle: "direct-path",
55 remoteScheme: "zed",
56 },
57 {
58 id: "antigravity",
59 label: "Antigravity",
60 // The IDE ships antigravity-ide; agy is the standalone CLI.
61 commands: ["antigravity-ide", "agy-ide"],
62 launchStyle: "goto",
63 },
64 {
65 id: "idea",
66 label: "IntelliJ IDEA",
67 commands: ["idea"],
68 launchStyle: "line-column",
69 jetbrainsProductCode: "IU",
70 },
71 {
72 id: "aqua",
73 label: "Aqua",
74 commands: ["aqua"],
75 launchStyle: "line-column",
76 jetbrainsProductCode: "QA",
77 },
78 {
79 id: "clion",
80 label: "CLion",
81 commands: ["clion"],
82 launchStyle: "line-column",
83 jetbrainsProductCode: "CL",
84 },
85 {
86 id: "datagrip",
87 label: "DataGrip",
88 commands: ["datagrip"],
89 launchStyle: "line-column",
90 jetbrainsProductCode: "DB",
91 },
92 {
93 id: "dataspell",
94 label: "DataSpell",
95 commands: ["dataspell"],
96 launchStyle: "line-column",
97 jetbrainsProductCode: "DS",
98 },
99 {
100 id: "goland",
101 label: "GoLand",
102 commands: ["goland"],
103 launchStyle: "line-column",
104 jetbrainsProductCode: "GO",
105 },
106 {
107 id: "phpstorm",
108 label: "PhpStorm",
109 commands: ["phpstorm"],
110 launchStyle: "line-column",
111 jetbrainsProductCode: "PS",
112 },
113 {
114 id: "pycharm",
115 label: "PyCharm",
116 commands: ["pycharm"],
117 launchStyle: "line-column",
118 jetbrainsProductCode: "PY",
119 },
120 {
121 id: "rider",
122 label: "Rider",
123 commands: ["rider"],
124 launchStyle: "line-column",
125 jetbrainsProductCode: "RD",
126 },
127 {
128 id: "rubymine",
129 label: "RubyMine",
130 commands: ["rubymine"],
131 launchStyle: "line-column",
132 jetbrainsProductCode: "RM",
133 },
134 {
135 id: "rustrover",
136 label: "RustRover",
137 commands: ["rustrover"],
138 launchStyle: "line-column",
139 jetbrainsProductCode: "RR",
140 },
141 {
142 id: "webstorm",
143 label: "WebStorm",
144 commands: ["webstorm"],
145 launchStyle: "line-column",
146 jetbrainsProductCode: "WS",
147 },
148 { id: "file-manager", label: "File Manager", commands: null, launchStyle: "direct-path" },
149] as const satisfies ReadonlyArray<EditorDefinition>;
150​
151export const EditorId = Schema.Literals(EDITORS.map((e) => e.id));
152export type EditorId = typeof EditorId.Type;
153​
154export const FileManagerRevealKind = Schema.Literals(["finder", "file-explorer", "files"]);
155export type FileManagerRevealKind = typeof FileManagerRevealKind.Type;
156​
157export const LaunchEditorInput = Schema.Struct({
158 cwd: TrimmedNonEmptyString,
159 editor: EditorId,
160 /** When present, cwd is an exact path; {} opens it without a position. Omit for diagnostic suffix parsing. */
161 position: Schema.optional(
162 Schema.Struct({
163 line: Schema.optional(PositiveInt),
164 column: Schema.optional(PositiveInt),
165 }),
166 ),
167 /** Workspace the target belongs to; JetBrains IDEs open positioned files in this project. */
168 projectRoot: Schema.optional(TrimmedNonEmptyString),
169 /** Only for file-manager; requires the server's shellRevealInFileManager capability. */
170 reveal: Schema.optional(Schema.Boolean),
171});
172export type LaunchEditorInput = typeof LaunchEditorInput.Type;
173​
174const remoteSchemeOf = (editor: EditorDefinition): string | undefined =>
175 editor.remoteScheme ?? (editor.jetbrainsProductCode === undefined ? undefined : "jetbrains");
176​
177export const REMOTE_CAPABLE_EDITOR_IDS: ReadonlyArray<EditorId> = EDITORS.flatMap((editor) =>
178 remoteSchemeOf(editor) !== undefined ? [editor.id] : [],
179);
180​
181export const remoteSchemeForEditor = (id: EditorId): string | undefined => {
182 const editor = EDITORS.find((candidate) => candidate.id === id);
183 return editor === undefined ? undefined : remoteSchemeOf(editor);
184};
185​
186// `goto` editors share VS Code's `file:line:col` addressing, so their remote schemes also open
187// a local file as `<scheme>://file/<absolute path>[:line[:col]]`. Zed and JetBrains differ.
188export const LOCAL_FILE_LINK_SCHEMES: ReadonlyArray<string> = EDITORS.flatMap((editor) =>
189 editor.launchStyle === "goto" && "remoteScheme" in editor ? [editor.remoteScheme] : [],
190);
191​
192export const isLocalEditorFileUrl = (url: URL): boolean =>
193 LOCAL_FILE_LINK_SCHEMES.includes(url.protocol.slice(0, -1)) &&
194 url.host === "file" &&
195 url.username.length === 0 &&
196 url.password.length === 0 &&
197 url.pathname.length > 1;
198​
199export const buildRemoteOpenUrl = (input: {
200 readonly editor: EditorId;
201 readonly host: string;
202 readonly username?: string;
203 readonly absolutePath: string;
204 readonly isFile?: boolean;
205}): string | undefined => {
206 const scheme = remoteSchemeForEditor(input.editor);
207 if (scheme === undefined) {
208 return undefined;
209 }
210 const editor = EDITORS.find((candidate) => candidate.id === input.editor);
211 if (editor !== undefined && "jetbrainsProductCode" in editor) {
212 const params = new URLSearchParams({
213 h: input.host,
214 launchIde: "true",
215 ideHint: editor.jetbrainsProductCode,
216 projectHint: input.absolutePath.replaceAll("\\", "/"),
217 });
218 if (input.username !== undefined) {
219 params.set("u", input.username);
220 }
221 return `${scheme}://gateway/ssh/environment?${params.toString()}`;
222 }
223 // Windows server paths (`C:\...`) appear as `/C:/...` in vscode-remote URIs.
224 const posixPath = input.absolutePath.replaceAll("\\", "/");
225 const rootedPath = posixPath.startsWith("/") ? posixPath : `/${posixPath}`;
226 const encodedHost = encodeURIComponent(input.host);
227 if (input.editor === "zed") {
228 // Zed roots paths on the system drive, so omit the Windows drive prefix.
229 const zedPath = /^[Cc]:[\\/]/.test(input.absolutePath) ? rootedPath.slice(3) : rootedPath;
230 const encodedZedPath = zedPath.split("/").map(encodeURIComponent).join("/");
231 // Zed reads this segment as ssh URL userinfo, so the `@` stays literal.
232 const zedDestination =
233 input.username === undefined
234 ? encodedHost
235 : `${encodeURIComponent(input.username)}@${encodedHost}`;
236 return `${scheme}://ssh/${zedDestination}${encodedZedPath}`;
237 }
238 const encodedPath = rootedPath.split("/").map(encodeURIComponent).join("/");
239 const plainDestination =
240 input.username === undefined ? input.host : `${input.username}@${input.host}`;
241 // Remote-SSH splits the decoded authority on "+", so a destination containing one must use its
242 // hex-encoded JSON form instead.
243 const destination = plainDestination.includes("+")
244 ? Array.from(
245 new TextEncoder().encode(JSON.stringify({ hostName: input.host, user: input.username })),
246 (byte) => byte.toString(16).padStart(2, "0"),
247 ).join("")
248 : plainDestination;
249 // VS Code opens a bare vscode-remote path as a folder; a trailing position makes it open the file.
250 // Without windowId=_blank, a folder link replaces the user's last active window.
251 return `${scheme}://vscode-remote/ssh-remote+${encodeURIComponent(destination)}${encodedPath}${input.isFile ? ":1:1" : "?windowId=_blank"}`;
252};
253​
254export const RemoteOpenTargetKind = Schema.Literals(["tailscale", "mdns"]);
255export type RemoteOpenTargetKind = typeof RemoteOpenTargetKind.Type;
256​
257export const RemoteOpenTarget = Schema.Struct({
258 kind: RemoteOpenTargetKind,
259 host: TrimmedNonEmptyString,
260 username: Schema.optionalKey(TrimmedNonEmptyString),
261});
262export type RemoteOpenTarget = typeof RemoteOpenTarget.Type;
263​
264export class ExternalLauncherUnknownEditorError extends Schema.TaggedError<ExternalLauncherUnknownEditorError>()(
265 "ExternalLauncherUnknownEditorError",
266 {
267 editor: Schema.String,
268 },
269) {
270 override get message(): string {
271 return `Unknown editor: ${this.editor}`;
272 }
274​
275export class ExternalLauncherUnsupportedEditorError extends Schema.TaggedError<ExternalLauncherUnsupportedEditorError>()(
276 "ExternalLauncherUnsupportedEditorError",
277 {
278 editor: EditorId,
279 },
280) {
281 override get message(): string {
282 return `Unsupported editor: ${this.editor}`;
283 }
285​
286export class ExternalLauncherCommandNotFoundError extends Schema.TaggedError<ExternalLauncherCommandNotFoundError>()(
287 "ExternalLauncherCommandNotFoundError",
288 {
289 editor: EditorId,
290 command: Schema.String,
291 },
292) {
293 override get message(): string {
294 return `Editor command not found: ${this.command}`;
295 }
297​
298export class ExternalLauncherUnsupportedTargetError extends Schema.TaggedError<ExternalLauncherUnsupportedTargetError>()(
299 "ExternalLauncherUnsupportedTargetError",
300 {
301 editor: EditorId,
302 },
303) {
304 override get message(): string {
305 return `${this.editor} cannot open a path containing line breaks or double quotes`;
306 }
308​
309export class ExternalLauncherRevealTargetMissingError extends Schema.TaggedError<ExternalLauncherRevealTargetMissingError>()(
310 "ExternalLauncherRevealTargetMissingError",
311 {
312 editor: EditorId,
313 target: Schema.String,
314 },
315) {
316 override get message(): string {
317 return `No file or folder exists at ${this.target}`;
318 }
320​
321const ExternalLauncherSpawnFields = {
322 command: Schema.String,
323 args: Schema.Array(Schema.String),
324 cause: Schema.Defect(),
325};
326​
327export class ExternalLauncherBrowserSpawnError extends Schema.TaggedError<ExternalLauncherBrowserSpawnError>()(
328 "ExternalLauncherBrowserSpawnError",
329 {
330 ...ExternalLauncherSpawnFields,
331 target: Schema.String,
332 },
333) {
334 override get message(): string {
335 return `Failed to launch browser target '${this.target}' with '${[this.command, ...this.args].join(" ")}'`;
336 }
338​
339export class ExternalLauncherEditorSpawnError extends Schema.TaggedError<ExternalLauncherEditorSpawnError>()(
340 "ExternalLauncherEditorSpawnError",
341 {
342 ...ExternalLauncherSpawnFields,
343 editor: EditorId,
344 target: Schema.String,
345 },
346) {
347 override get message(): string {
348 return `Failed to launch '${this.target}' in ${this.editor} with '${[this.command, ...this.args].join(" ")}'`;
349 }
351​
352export const ExternalLauncherError = Schema.Union([
353 ExternalLauncherUnknownEditorError,
354 ExternalLauncherUnsupportedEditorError,
355 ExternalLauncherCommandNotFoundError,
356 ExternalLauncherUnsupportedTargetError,
357 ExternalLauncherRevealTargetMissingError,
358 ExternalLauncherBrowserSpawnError,
359 ExternalLauncherEditorSpawnError,
360]);
361export type ExternalLauncherError = typeof ExternalLauncherError.Type;