Open History to see the last commit
1import * as Cause from "effect/Cause";
2import * as Context from "effect/Context";
3import * as Data from "effect/Data";
4import * as Effect from "effect/Effect";
5import * as FileSystem from "effect/FileSystem";
6import * as Layer from "effect/Layer";
7import * as Option from "effect/Option";
8import * as Ref from "effect/Ref";
9import * as Scope from "effect/Scope";
10
11import * as Electron from "electron";
12
13import { DesktopEnvironment, type DesktopEnvironmentShape } from "../app/DesktopEnvironment.ts";
14
15export const DESKTOP_SCHEME = "t3";
16
17export class ElectronProtocolRegistrationError extends Data.TaggedError(
18 "ElectronProtocolRegistrationError",
19)<{
20 readonly scheme: string;
21 readonly cause: unknown;
22}> {
23 override get message() {
24 return `Failed to register ${this.scheme}: file protocol.`;
25 }
26}
27
28export class ElectronProtocolStaticBundleMissingError extends Data.TaggedError(
29 "ElectronProtocolStaticBundleMissingError",
30)<{}> {
31 override get message() {
32 return "Desktop static bundle missing. Build apps/server (with bundled client) first.";
33 }
34}
35
36export interface ElectronProtocolShape {
37 readonly registerFileProtocol: <E, R>(input: {
38 readonly scheme: string;
39 readonly handler: (
40 request: Electron.ProtocolRequest,
41 ) => Effect.Effect<Electron.ProtocolResponse, E, R>;
42 readonly onFailure?: (
43 request: Electron.ProtocolRequest,
44 cause: Cause.Cause<E>,
45 ) => Electron.ProtocolResponse;
46 }) => Effect.Effect<void, ElectronProtocolRegistrationError, R | Scope.Scope>;
47 readonly registerDesktopFileProtocol: Effect.Effect<
48 void,
49 ElectronProtocolRegistrationError | ElectronProtocolStaticBundleMissingError,
50 FileSystem.FileSystem | DesktopEnvironment | Scope.Scope
51 >;
52}
53
54export class ElectronProtocol extends Context.Service<ElectronProtocol, ElectronProtocolShape>()(
55 "t3/desktop/electron/Protocol",
56) {}
57
58export function normalizeDesktopProtocolPathname(rawPath: string): Option.Option<string> {
59 const segments: string[] = [];
60 for (const segment of rawPath.split("/")) {
61 if (segment.length === 0 || segment === ".") {
62 continue;
63 }
64 if (segment === "..") {
65 return Option.none();
66 }
67 segments.push(segment);
68 }
69 return Option.some(segments.join("/"));
70}
71
72const registerDesktopSchemePrivileges = Effect.sync(() => {
73 Electron.protocol.registerSchemesAsPrivileged([
74 {
75 scheme: DESKTOP_SCHEME,
76 privileges: {
77 standard: true,
78 secure: true,
79 supportFetchAPI: true,
80 corsEnabled: true,
81 },
82 },
83 ]);
84}).pipe(Effect.withSpan("desktop.electron.protocol.registerSchemePrivileges"));
85
86export const layerSchemePrivileges = Layer.effectDiscard(registerDesktopSchemePrivileges);
87
88const resolveDesktopStaticDir: Effect.Effect<
89 Option.Option<string>,
90 never,
91 FileSystem.FileSystem | DesktopEnvironment
92> = Effect.gen(function* () {
93 const fileSystem = yield* FileSystem.FileSystem;
94 const environment = yield* DesktopEnvironment;
95 const candidates = [
96 environment.path.join(environment.appRoot, "apps/server/dist/client"),
97 environment.path.join(environment.appRoot, "apps/web/dist"),
98 ];
99 for (const candidate of candidates) {
100 const hasIndex = yield* fileSystem
101 .exists(environment.path.join(candidate, "index.html"))
102 .pipe(Effect.orElseSucceed(() => false));
103 if (hasIndex) {
104 return Option.some(candidate);
105 }
106 }
107 return Option.none<string>();
108});
109
110const resolveDesktopStaticPath = Effect.fn("desktop.electron.protocol.resolveDesktopStaticPath")(
111 function* (
112 staticRoot: string,
113 requestUrl: string,
114 ): Effect.fn.Return<string, never, FileSystem.FileSystem | DesktopEnvironment> {
115 const fileSystem = yield* FileSystem.FileSystem;
116 const environment = yield* DesktopEnvironment;
117 const url = new URL(requestUrl);
118 const rawPath = decodeURIComponent(url.pathname);
119 const normalizedPath = normalizeDesktopProtocolPathname(rawPath);
120 if (Option.isNone(normalizedPath)) {
121 return environment.path.join(staticRoot, "index.html");
122 }
123
124 const requestedPath = normalizedPath.value.length > 0 ? normalizedPath.value : "index.html";
125 const resolvedPath = environment.path.join(staticRoot, requestedPath);
126
127 if (environment.path.extname(resolvedPath)) {
128 return resolvedPath;
129 }
130
131 const nestedIndex = environment.path.join(resolvedPath, "index.html");
132 const nestedIndexExists = yield* fileSystem
133 .exists(nestedIndex)
134 .pipe(Effect.orElseSucceed(() => false));
135 if (nestedIndexExists) {
136 return nestedIndex;
137 }
138
139 return environment.path.join(staticRoot, "index.html");
140 },
141);
142
143function isStaticAssetRequest(requestUrl: string, environment: DesktopEnvironmentShape): boolean {
144 try {
145 const url = new URL(requestUrl);
146 return environment.path.extname(url.pathname).length > 0;
147 } catch {
148 return false;
149 }
150}
151
152const make = Effect.gen(function* () {
153 const registeredProtocols = yield* Ref.make<ReadonlySet<string>>(new Set());
154
155 const registerFileProtocol = Effect.fn("desktop.electron.protocol.registerFileProtocol")(
156 function* <E, R>({
157 scheme,
158 handler,
159 onFailure,
160 }: {
161 readonly scheme: string;
162 readonly handler: (
163 request: Electron.ProtocolRequest,
164 ) => Effect.Effect<Electron.ProtocolResponse, E, R>;
165 readonly onFailure?: (
166 request: Electron.ProtocolRequest,
167 cause: Cause.Cause<E>,
168 ) => Electron.ProtocolResponse;
169 }): Effect.fn.Return<void, ElectronProtocolRegistrationError, R | Scope.Scope> {
170 yield* Effect.annotateCurrentSpan({ scheme });
171 const alreadyRegistered = yield* Ref.get(registeredProtocols).pipe(
172 Effect.map((protocols) => protocols.has(scheme)),
173 );
174 if (alreadyRegistered) {
175 return;
176 }
177
178 const context = yield* Effect.context<R>();
179 const runPromise = Effect.runPromiseWith(context);
180
181 yield* Effect.acquireRelease(
182 Effect.try({
183 try: () => {
184 const registered = Electron.protocol.registerFileProtocol(
185 scheme,
186 (request, callback) => {
187 const response = handler(request).pipe(
188 Effect.withSpan("desktop.electron.protocol.handleFileRequest"),
189 Effect.catchCause((cause) =>
190 Effect.succeed(onFailure?.(request, cause) ?? ({ error: -2 } as const)),
191 ),
192 );
193
194 void runPromise(response).then(callback, () => callback({ error: -2 }));
195 },
196 );
197 if (!registered) {
198 throw new ElectronProtocolRegistrationError({
199 scheme,
200 cause: "registerFileProtocol returned false",
201 });
202 }
203 },
204 catch: (cause) =>
205 cause instanceof ElectronProtocolRegistrationError
206 ? cause
207 : new ElectronProtocolRegistrationError({ scheme, cause }),
208 }).pipe(
209 Effect.andThen(
210 Ref.update(registeredProtocols, (protocols) => new Set(protocols).add(scheme)),
211 ),
212 ),
213 () =>
214 Effect.sync(() => {
215 Electron.protocol.unregisterProtocol(scheme);
216 }).pipe(
217 Effect.andThen(
218 Ref.update(registeredProtocols, (protocols) => {
219 const next = new Set(protocols);
220 next.delete(scheme);
221 return next;
222 }),
223 ),
224 ),
225 );
226 },
227 );
228
229 const registerDesktopFileProtocol = Effect.gen(function* () {
230 const environment = yield* DesktopEnvironment;
231 if (environment.isDevelopment) return;
232
233 const staticRoot = yield* resolveDesktopStaticDir;
234 if (Option.isNone(staticRoot)) {
235 return yield* new ElectronProtocolStaticBundleMissingError();
236 }
237
238 const staticRootResolved = environment.path.resolve(staticRoot.value);
239 const staticRootPrefix = `${staticRootResolved}${environment.path.sep}`;
240 const fallbackIndex = environment.path.join(staticRootResolved, "index.html");
241
242 yield* registerFileProtocol({
243 scheme: DESKTOP_SCHEME,
244 handler: Effect.fn("desktop.electron.protocol.handleDesktopFileRequest")(function* (request) {
245 const fileSystem = yield* FileSystem.FileSystem;
246 const environment = yield* DesktopEnvironment;
247 const candidate = yield* resolveDesktopStaticPath(staticRootResolved, request.url);
248 const resolvedCandidate = environment.path.resolve(candidate);
249 const isInRoot =
250 resolvedCandidate === fallbackIndex || resolvedCandidate.startsWith(staticRootPrefix);
251 const isAssetRequest = isStaticAssetRequest(request.url, environment);
252 const exists = yield* fileSystem
253 .exists(resolvedCandidate)
254 .pipe(Effect.orElseSucceed(() => false));
255
256 if (!isInRoot || !exists) {
257 return isAssetRequest ? ({ error: -6 } as const) : ({ path: fallbackIndex } as const);
258 }
259
260 return { path: resolvedCandidate } as const;
261 }),
262 onFailure: () => ({ path: fallbackIndex }),
263 });
264 }).pipe(Effect.withSpan("desktop.electron.protocol.registerDesktopFileProtocol"));
265
266 return ElectronProtocol.of({
267 registerFileProtocol,
268 registerDesktopFileProtocol,
269 });
270});
271
272export const layer = Layer.effect(ElectronProtocol, make);