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

editor.ts

338 lines10.4 KB

1import * as Schema from "effect/Schema";
2import { 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 /** Only for file-manager; requires the server's shellRevealInFileManager capability. */
161 reveal: Schema.optional(Schema.Boolean),
162});
163export type LaunchEditorInput = typeof LaunchEditorInput.Type;
164​
165const remoteSchemeOf = (editor: EditorDefinition): string | undefined =>
166 editor.remoteScheme ?? (editor.jetbrainsProductCode === undefined ? undefined : "jetbrains");
167​
168export const REMOTE_CAPABLE_EDITOR_IDS: ReadonlyArray<EditorId> = EDITORS.flatMap((editor) =>
169 remoteSchemeOf(editor) !== undefined ? [editor.id] : [],
170);
171​
172export const remoteSchemeForEditor = (id: EditorId): string | undefined => {
173 const editor = EDITORS.find((candidate) => candidate.id === id);
174 return editor === undefined ? undefined : remoteSchemeOf(editor);
175};
176​
177// `goto` editors share VS Code's `file:line:col` addressing, so their remote schemes also open
178// a local file as `<scheme>://file/<absolute path>[:line[:col]]`. Zed and JetBrains differ.
179export const LOCAL_FILE_LINK_SCHEMES: ReadonlyArray<string> = EDITORS.flatMap((editor) =>
180 editor.launchStyle === "goto" && "remoteScheme" in editor ? [editor.remoteScheme] : [],
181);
182​
183export const isLocalEditorFileUrl = (url: URL): boolean =>
184 LOCAL_FILE_LINK_SCHEMES.includes(url.protocol.slice(0, -1)) &&
185 url.host === "file" &&
186 url.username.length === 0 &&
187 url.password.length === 0 &&
188 url.pathname.length > 1;
189​
190export const buildRemoteOpenUrl = (input: {
191 readonly editor: EditorId;
192 readonly host: string;
193 readonly username?: string;
194 readonly absolutePath: string;
195 readonly isFile?: boolean;
196}): string | undefined => {
197 const scheme = remoteSchemeForEditor(input.editor);
198 if (scheme === undefined) {
199 return undefined;
200 }
201 const editor = EDITORS.find((candidate) => candidate.id === input.editor);
202 if (editor !== undefined && "jetbrainsProductCode" in editor) {
203 const params = new URLSearchParams({
204 h: input.host,
205 launchIde: "true",
206 ideHint: editor.jetbrainsProductCode,
207 projectHint: input.absolutePath.replaceAll("\\", "/"),
208 });
209 if (input.username !== undefined) {
210 params.set("u", input.username);
211 }
212 return `${scheme}://gateway/ssh/environment?${params.toString()}`;
213 }
214 // Windows server paths (`C:\...`) appear as `/C:/...` in vscode-remote URIs.
215 const posixPath = input.absolutePath.replaceAll("\\", "/");
216 const rootedPath = posixPath.startsWith("/") ? posixPath : `/${posixPath}`;
217 const encodedHost = encodeURIComponent(input.host);
218 if (input.editor === "zed") {
219 // Zed roots paths on the system drive, so omit the Windows drive prefix.
220 const zedPath = /^[Cc]:[\\/]/.test(input.absolutePath) ? rootedPath.slice(3) : rootedPath;
221 const encodedZedPath = zedPath.split("/").map(encodeURIComponent).join("/");
222 // Zed reads this segment as ssh URL userinfo, so the `@` stays literal.
223 const zedDestination =
224 input.username === undefined
225 ? encodedHost
226 : `${encodeURIComponent(input.username)}@${encodedHost}`;
227 return `${scheme}://ssh/${zedDestination}${encodedZedPath}`;
228 }
229 const encodedPath = rootedPath.split("/").map(encodeURIComponent).join("/");
230 const plainDestination =
231 input.username === undefined ? input.host : `${input.username}@${input.host}`;
232 // Remote-SSH splits the decoded authority on "+", so a destination containing one must use its
233 // hex-encoded JSON form instead.
234 const destination = plainDestination.includes("+")
235 ? Array.from(
236 new TextEncoder().encode(JSON.stringify({ hostName: input.host, user: input.username })),
237 (byte) => byte.toString(16).padStart(2, "0"),
238 ).join("")
239 : plainDestination;
240 // VS Code opens a bare vscode-remote path as a folder; a trailing position makes it open the file.
241 return `${scheme}://vscode-remote/ssh-remote+${encodeURIComponent(destination)}${encodedPath}${input.isFile ? ":1:1" : ""}`;
242};
243​
244export const RemoteOpenTargetKind = Schema.Literals(["tailscale", "mdns"]);
245export type RemoteOpenTargetKind = typeof RemoteOpenTargetKind.Type;
246​
247export const RemoteOpenTarget = Schema.Struct({
248 kind: RemoteOpenTargetKind,
249 host: TrimmedNonEmptyString,
250 username: Schema.optionalKey(TrimmedNonEmptyString),
251});
252export type RemoteOpenTarget = typeof RemoteOpenTarget.Type;
253​
254export class ExternalLauncherUnknownEditorError extends Schema.TaggedError<ExternalLauncherUnknownEditorError>()(
255 "ExternalLauncherUnknownEditorError",
256 {
257 editor: Schema.String,
258 },
259) {
260 override get message(): string {
261 return `Unknown editor: ${this.editor}`;
262 }
264​
265export class ExternalLauncherUnsupportedEditorError extends Schema.TaggedError<ExternalLauncherUnsupportedEditorError>()(
266 "ExternalLauncherUnsupportedEditorError",
267 {
268 editor: EditorId,
269 },
270) {
271 override get message(): string {
272 return `Unsupported editor: ${this.editor}`;
273 }
275​
276export class ExternalLauncherCommandNotFoundError extends Schema.TaggedError<ExternalLauncherCommandNotFoundError>()(
277 "ExternalLauncherCommandNotFoundError",
278 {
279 editor: EditorId,
280 command: Schema.String,
281 },
282) {
283 override get message(): string {
284 return `Editor command not found: ${this.command}`;
285 }
287​
288export class ExternalLauncherUnsupportedTargetError extends Schema.TaggedError<ExternalLauncherUnsupportedTargetError>()(
289 "ExternalLauncherUnsupportedTargetError",
290 {
291 editor: EditorId,
292 },
293) {
294 override get message(): string {
295 return `${this.editor} cannot open a path containing line breaks or double quotes`;
296 }
298​
299const ExternalLauncherSpawnFields = {
300 command: Schema.String,
301 args: Schema.Array(Schema.String),
302 cause: Schema.Defect(),
303};
304​
305export class ExternalLauncherBrowserSpawnError extends Schema.TaggedError<ExternalLauncherBrowserSpawnError>()(
306 "ExternalLauncherBrowserSpawnError",
307 {
308 ...ExternalLauncherSpawnFields,
309 target: Schema.String,
310 },
311) {
312 override get message(): string {
313 return `Failed to launch browser target '${this.target}' with '${[this.command, ...this.args].join(" ")}'`;
314 }
316​
317export class ExternalLauncherEditorSpawnError extends Schema.TaggedError<ExternalLauncherEditorSpawnError>()(
318 "ExternalLauncherEditorSpawnError",
319 {
320 ...ExternalLauncherSpawnFields,
321 editor: EditorId,
322 target: Schema.String,
323 },
324) {
325 override get message(): string {
326 return `Failed to launch '${this.target}' in ${this.editor} with '${[this.command, ...this.args].join(" ")}'`;
327 }
329​
330export const ExternalLauncherError = Schema.Union([
331 ExternalLauncherUnknownEditorError,
332 ExternalLauncherUnsupportedEditorError,
333 ExternalLauncherCommandNotFoundError,
334 ExternalLauncherUnsupportedTargetError,
335 ExternalLauncherBrowserSpawnError,
336 ExternalLauncherEditorSpawnError,
337]);
338export type ExternalLauncherError = typeof ExternalLauncherError.Type;