Open History to see the last commit
1import { REMOTE_CAPABLE_EDITOR_IDS, remoteSchemeForEditor } from "@t3tools/contracts";
2import * as Context from "effect/Context";
3import * as Effect from "effect/Effect";
4import * as Layer from "effect/Layer";
5import * as Option from "effect/Option";
6
7import * as Electron from "electron";
8
9// Remote open-in-editor deep links (`vscode://vscode-remote/ssh-remote+…`)
10// must reach the OS handler; every other non-web scheme stays blocked.
11const SAFE_EXTERNAL_PROTOCOLS = new Set([
12 "http:",
13 "https:",
14 ...REMOTE_CAPABLE_EDITOR_IDS.flatMap((id) => {
15 const scheme = remoteSchemeForEditor(id);
16 return scheme === undefined ? [] : [`${scheme}:`];
17 }),
18]);
19
20export function parseSafeExternalUrl(rawUrl: unknown): Option.Option<string> {
21 if (typeof rawUrl !== "string") {
22 return Option.none();
23 }
24
25 try {
26 const url = new URL(rawUrl);
27 return SAFE_EXTERNAL_PROTOCOLS.has(url.protocol) ? Option.some(url.href) : Option.none();
28 } catch {
29 return Option.none();
30 }
31}
32
33export class ElectronShell extends Context.Service<
34 ElectronShell,
35 {
36 readonly openExternal: (rawUrl: unknown) => Effect.Effect<boolean>;
37 readonly copyText: (text: string) => Effect.Effect<void>;
38 }
39>()("@t3tools/desktop/electron/ElectronShell") {}
40
41export const make = ElectronShell.of({
42 openExternal: (rawUrl) =>
43 Option.match(parseSafeExternalUrl(rawUrl), {
44 onNone: () => Effect.succeed(false),
45 onSome: (externalUrl) =>
46 Effect.promise(() =>
47 Electron.shell.openExternal(externalUrl).then(
48 () => true,
49 () => false,
50 ),
51 ),
52 }),
53 copyText: (text) =>
54 Effect.sync(() => {
55 Electron.clipboard.writeText(text);
56 }),
57});
58
59export const layer = Layer.succeed(ElectronShell, make);