Open History to see the last commit
1import path from "node:path";
2import { Effect, FileSystem, Layer, Option } from "effect";
3import * as PlatformError from "effect/PlatformError";
4
5import { VcsDriverRegistry } from "../../vcs/VcsDriverRegistry.ts";
6import {
7 ProjectFaviconResolver,
8 type ProjectFaviconResolverShape,
9} from "../Services/ProjectFaviconResolver.ts";
10
11// Well-known favicon paths checked in order.
12const FAVICON_CANDIDATES = [
13 "favicon.svg",
14 "favicon.ico",
15 "favicon.png",
16 "public/favicon.svg",
17 "public/favicon.ico",
18 "public/favicon.png",
19 "app/favicon.ico",
20 "app/favicon.png",
21 "app/icon.svg",
22 "app/icon.png",
23 "app/icon.ico",
24 "src/favicon.ico",
25 "src/favicon.svg",
26 "src/app/favicon.ico",
27 "src/app/icon.svg",
28 "src/app/icon.png",
29 "assets/icon.svg",
30 "assets/icon.png",
31 "assets/logo.svg",
32 "assets/logo.png",
33 ".idea/icon.svg",
34] as const;
35
36// Files that may contain a <link rel="icon"> or icon metadata declaration.
37const ICON_SOURCE_FILES = [
38 "index.html",
39 "public/index.html",
40 "app/routes/__root.tsx",
41 "src/routes/__root.tsx",
42 "app/root.tsx",
43 "src/root.tsx",
44 "src/index.html",
45] as const;
46
47// Matches <link ...> tags or object-like icon metadata where rel/href can appear in any order.
48const LINK_ICON_HTML_RE =
49 /<link\b(?=[^>]*\brel=["'](?:icon|shortcut icon)["'])(?=[^>]*\bhref=["']([^"'?]+))[^>]*>/i;
50const LINK_ICON_OBJ_RE =
51 /(?=[^}]*\brel\s*:\s*["'](?:icon|shortcut icon)["'])(?=[^}]*\bhref\s*:\s*["']([^"'?]+))[^}]*/i;
52const IGNORED_WORKSPACE_DIRECTORY_NAMES = new Set([
53 ".git",
54 ".convex",
55 "node_modules",
56 ".next",
57 ".turbo",
58 "dist",
59 "build",
60 "out",
61 ".cache",
62]);
63
64type ExistingPathType = "File" | "Directory";
65
66interface FaviconLookupServices {
67 fileSystem: FileSystem.FileSystem;
68 projectRoot: string;
69 filterAllowedPaths: (candidatePaths: readonly string[]) => Effect.Effect<string[], never>;
70}
71
72function isPathInIgnoredWorkspaceDirectory(relativePath: string): boolean {
73 const firstSegment = relativePath.split("/")[0];
74 if (!firstSegment) {
75 return false;
76 }
77
78 return IGNORED_WORKSPACE_DIRECTORY_NAMES.has(firstSegment);
79}
80
81function extractIconHref(source: string): Option.Option<string> {
82 const htmlMatch = source.match(LINK_ICON_HTML_RE);
83 if (htmlMatch?.[1]) {
84 return Option.some(htmlMatch[1]);
85 }
86
87 const objectMatch = source.match(LINK_ICON_OBJ_RE);
88 if (objectMatch?.[1]) {
89 return Option.some(objectMatch[1]);
90 }
91
92 return Option.none();
93}
94
95function platformErrorToNone<A, R>(
96 effect: Effect.Effect<A, PlatformError.PlatformError, R>,
97): Effect.Effect<Option.Option<A>, never, R> {
98 return effect.pipe(
99 Effect.map(Option.some),
100 Effect.catchTag("PlatformError", () => Effect.succeed(Option.none<A>())),
101 );
102}
103
104function toProjectRelativePath(projectRoot: string, candidatePath: string): Option.Option<string> {
105 const relativePath = path.relative(projectRoot, candidatePath);
106 if (relativePath.length === 0 || relativePath.startsWith("..") || path.isAbsolute(relativePath)) {
107 return Option.none();
108 }
109
110 return Option.some(relativePath.split(path.sep).join("/"));
111}
112
113function resolveExistingPath(
114 lookup: Pick<FaviconLookupServices, "fileSystem" | "projectRoot">,
115 candidatePath: string,
116 expectedType: ExistingPathType,
117) {
118 return Effect.gen(function* () {
119 const resolvedPathOption = yield* platformErrorToNone(
120 lookup.fileSystem.realPath(candidatePath),
121 );
122 if (Option.isNone(resolvedPathOption)) {
123 return Option.none();
124 }
125
126 const resolvedPath = resolvedPathOption.value;
127 const relativePath = path.relative(lookup.projectRoot, resolvedPath);
128 if (relativePath !== "" && (relativePath.startsWith("..") || path.isAbsolute(relativePath))) {
129 return Option.none();
130 }
131
132 const infoOption = yield* platformErrorToNone(lookup.fileSystem.stat(resolvedPath));
133 if (Option.isNone(infoOption) || infoOption.value.type !== expectedType) {
134 return Option.none();
135 }
136
137 return Option.some(resolvedPath);
138 });
139}
140
141function readFileIfExists<A>(
142 lookup: Pick<FaviconLookupServices, "fileSystem" | "projectRoot">,
143 candidatePath: string,
144 read: (resolvedPath: string) => Effect.Effect<A, PlatformError.PlatformError>,
145) {
146 return Effect.gen(function* () {
147 const resolvedPathOption = yield* resolveExistingPath(lookup, candidatePath, "File");
148 if (Option.isNone(resolvedPathOption)) {
149 return Option.none();
150 }
151
152 const contentOption = yield* platformErrorToNone(read(resolvedPathOption.value));
153 if (Option.isNone(contentOption)) {
154 return Option.none();
155 }
156
157 return Option.some({
158 path: resolvedPathOption.value,
159 content: contentOption.value,
160 });
161 });
162}
163
164function makeAllowedPathFilter(
165 projectRoot: string,
166 shouldFilterWithVcsIgnore: boolean,
167 filterVcsIgnoredPaths: (relativePaths: string[]) => Effect.Effect<string[], never>,
168) {
169 const gitIgnorePathCache = new Map<string, boolean>();
170
171 return (candidatePaths: readonly string[]) =>
172 Effect.gen(function* () {
173 if (!shouldFilterWithVcsIgnore || candidatePaths.length === 0) {
174 return [...candidatePaths];
175 }
176
177 const uncachedRelativePaths = Array.from(
178 new Set(
179 candidatePaths.flatMap((candidatePath) =>
180 Option.match(toProjectRelativePath(projectRoot, candidatePath), {
181 onNone: () => [],
182 onSome: (relativePath) =>
183 gitIgnorePathCache.has(relativePath) ? [] : [relativePath],
184 }),
185 ),
186 ),
187 );
188
189 if (uncachedRelativePaths.length > 0) {
190 const allowedRelativePaths = yield* filterVcsIgnoredPaths(uncachedRelativePaths);
191 const allowedRelativePathSet = new Set(allowedRelativePaths);
192
193 for (const relativePath of uncachedRelativePaths) {
194 gitIgnorePathCache.set(relativePath, allowedRelativePathSet.has(relativePath));
195 }
196 }
197
198 return candidatePaths.filter((candidatePath) =>
199 Option.match(toProjectRelativePath(projectRoot, candidatePath), {
200 onNone: () => true,
201 onSome: (relativePath) => gitIgnorePathCache.get(relativePath) !== false,
202 }),
203 );
204 });
205}
206
207function findFirstReadableFaviconPath(
208 lookup: FaviconLookupServices,
209 candidatePaths: readonly string[],
210) {
211 return Effect.gen(function* () {
212 const allowedCandidatePaths = yield* lookup.filterAllowedPaths(candidatePaths);
213
214 for (const candidatePath of allowedCandidatePaths) {
215 const fileOption = yield* readFileIfExists(lookup, candidatePath, (resolvedPath) =>
216 lookup.fileSystem.readFile(resolvedPath),
217 );
218 if (Option.isSome(fileOption)) {
219 return Option.some(fileOption.value.path);
220 }
221 }
222
223 return Option.none();
224 });
225}
226
227function iconHrefCandidatePaths(searchRoot: string, href: string): string[] {
228 const cleanHref = href.replace(/^\//, "");
229 return [path.join(searchRoot, "public", cleanHref), path.join(searchRoot, cleanHref)];
230}
231
232function findFaviconFromSourcePath(
233 lookup: FaviconLookupServices,
234 searchRoot: string,
235 sourcePath: string,
236) {
237 return Effect.gen(function* () {
238 const sourceFileOption = yield* readFileIfExists(lookup, sourcePath, (resolvedPath) =>
239 lookup.fileSystem.readFileString(resolvedPath),
240 );
241 if (Option.isNone(sourceFileOption)) {
242 return Option.none();
243 }
244
245 const hrefOption = extractIconHref(sourceFileOption.value.content);
246 if (Option.isNone(hrefOption)) {
247 return Option.none();
248 }
249
250 return yield* findFirstReadableFaviconPath(
251 lookup,
252 iconHrefCandidatePaths(searchRoot, hrefOption.value),
253 );
254 });
255}
256
257function findFaviconFromSourceFiles(lookup: FaviconLookupServices, searchRoot: string) {
258 return Effect.gen(function* () {
259 const sourcePaths = yield* lookup.filterAllowedPaths(
260 ICON_SOURCE_FILES.map((sourceFile) => path.join(searchRoot, sourceFile)),
261 );
262
263 for (const sourcePath of sourcePaths) {
264 const faviconPathOption = yield* findFaviconFromSourcePath(lookup, searchRoot, sourcePath);
265 if (Option.isSome(faviconPathOption)) {
266 return faviconPathOption;
267 }
268 }
269
270 return Option.none();
271 });
272}
273
274function findFaviconInSearchRoot(lookup: FaviconLookupServices, searchRoot: string) {
275 return Effect.gen(function* () {
276 const faviconPathOption = yield* findFirstReadableFaviconPath(
277 lookup,
278 FAVICON_CANDIDATES.map((candidate) => path.join(searchRoot, candidate)),
279 );
280 if (Option.isSome(faviconPathOption)) {
281 return faviconPathOption;
282 }
283
284 return yield* findFaviconFromSourceFiles(lookup, searchRoot);
285 });
286}
287
288function listChildDirectories(lookup: FaviconLookupServices, rootPath: string) {
289 return Effect.gen(function* () {
290 const entriesOption = yield* platformErrorToNone(lookup.fileSystem.readDirectory(rootPath));
291 if (Option.isNone(entriesOption)) {
292 return [];
293 }
294
295 const directories: string[] = [];
296 for (const entry of entriesOption.value.toSorted((left, right) => left.localeCompare(right))) {
297 if (entry.length === 0 || entry.includes("/") || entry.includes("\\")) {
298 continue;
299 }
300 if (isPathInIgnoredWorkspaceDirectory(entry)) {
301 continue;
302 }
303
304 const directoryPathOption = yield* resolveExistingPath(
305 lookup,
306 path.join(rootPath, entry),
307 "Directory",
308 );
309 if (Option.isSome(directoryPathOption)) {
310 directories.push(directoryPathOption.value);
311 }
312 }
313
314 return directories;
315 });
316}
317
318function listCandidateSearchRoots(lookup: FaviconLookupServices) {
319 return Effect.gen(function* () {
320 const [appRoots, packageRoots, directChildRoots] = yield* Effect.all([
321 listChildDirectories(lookup, path.join(lookup.projectRoot, "apps")),
322 listChildDirectories(lookup, path.join(lookup.projectRoot, "packages")),
323 listChildDirectories(lookup, lookup.projectRoot),
324 ]);
325
326 return [
327 ...appRoots,
328 ...packageRoots,
329 ...directChildRoots.filter((directChildRoot) => {
330 const baseName = path.basename(directChildRoot).toLowerCase();
331 return baseName !== "apps" && baseName !== "packages";
332 }),
333 ];
334 });
335}
336
337function findNestedFavicon(lookup: FaviconLookupServices) {
338 return Effect.gen(function* () {
339 const searchRoots = yield* listCandidateSearchRoots(lookup).pipe(
340 Effect.flatMap((roots) => lookup.filterAllowedPaths(roots)),
341 );
342
343 for (const searchRoot of searchRoots) {
344 const faviconPathOption = yield* findFaviconInSearchRoot(lookup, searchRoot);
345 if (Option.isSome(faviconPathOption)) {
346 return faviconPathOption;
347 }
348 }
349
350 return Option.none();
351 });
352}
353
354export const makeProjectFaviconResolver = Effect.gen(function* () {
355 const fileSystem = yield* FileSystem.FileSystem;
356 const vcsRegistry = yield* VcsDriverRegistry;
357
358 const isInsideVcsWorkTree = (cwd: string): Effect.Effect<boolean, never> =>
359 vcsRegistry.detect({ cwd }).pipe(
360 Effect.map((handle) => handle !== null),
361 Effect.catch(() => Effect.succeed(false)),
362 );
363
364 const filterVcsIgnoredPaths = (
365 cwd: string,
366 relativePaths: string[],
367 ): Effect.Effect<string[], never> =>
368 vcsRegistry.detect({ cwd }).pipe(
369 Effect.flatMap((handle) =>
370 handle
371 ? handle.driver.filterIgnoredPaths(cwd, relativePaths).pipe(
372 Effect.map((paths) => [...paths]),
373 Effect.catch(() => Effect.succeed(relativePaths)),
374 )
375 : Effect.succeed(relativePaths),
376 ),
377 Effect.catch(() => Effect.succeed(relativePaths)),
378 );
379
380 const resolvePath: ProjectFaviconResolverShape["resolvePath"] = Effect.fn(
381 "ProjectFaviconResolver.resolvePath",
382 )(function* (cwd): Effect.fn.Return<string | null> {
383 const projectRootOption = yield* platformErrorToNone(fileSystem.realPath(cwd));
384 if (Option.isNone(projectRootOption)) {
385 return null;
386 }
387
388 const projectRoot = projectRootOption.value;
389 const shouldFilterWithVcsIgnore = yield* isInsideVcsWorkTree(projectRoot);
390 const lookup = {
391 fileSystem,
392 projectRoot,
393 filterAllowedPaths: makeAllowedPathFilter(projectRoot, shouldFilterWithVcsIgnore, (paths) =>
394 filterVcsIgnoredPaths(projectRoot, paths),
395 ),
396 } satisfies FaviconLookupServices;
397
398 const rootFaviconOption = yield* findFaviconInSearchRoot(lookup, projectRoot);
399 if (Option.isSome(rootFaviconOption)) {
400 return rootFaviconOption.value;
401 }
402
403 const nestedFaviconOption = yield* findNestedFavicon(lookup);
404 if (Option.isSome(nestedFaviconOption)) {
405 return nestedFaviconOption.value;
406 }
407
408 return null;
409 });
410
411 return {
412 resolvePath,
413 } satisfies ProjectFaviconResolverShape;
414});
415
416export const ProjectFaviconResolverLive = Layer.effect(
417 ProjectFaviconResolver,
418 makeProjectFaviconResolver,
419);