Open History to see the last commit
1/**
2 * ProjectFaviconResolver - Effect service contract for project icon discovery.
3 *
4 * Resolves a representative favicon or app icon file for a workspace by
5 * checking common file locations and project source metadata.
6 *
7 * @module ProjectFaviconResolver
8 */
9import * as Context from "effect/Context";
10import * as Effect from "effect/Effect";
11import * as FileSystem from "effect/FileSystem";
12import * as Layer from "effect/Layer";
13import * as Option from "effect/Option";
14import * as Path from "effect/Path";
15import * as PlatformError from "effect/PlatformError";
16import * as Schema from "effect/Schema";
17
18import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
19
20// Well-known favicon paths checked in order.
21const FAVICON_CANDIDATES = [
22 "favicon.svg",
23 "favicon.ico",
24 "favicon.png",
25 "public/favicon.svg",
26 "public/favicon.ico",
27 "public/favicon.png",
28 "app/favicon.ico",
29 "app/favicon.png",
30 "app/icon.svg",
31 "app/icon.png",
32 "app/icon.ico",
33 "src/favicon.ico",
34 "src/favicon.svg",
35 "src/app/favicon.ico",
36 "src/app/icon.svg",
37 "src/app/icon.png",
38 "assets/icon.svg",
39 "assets/icon.png",
40 "assets/logo.svg",
41 "assets/logo.png",
42 ".idea/icon.svg",
43] as const;
44
45// Files that may contain a <link rel="icon"> or icon metadata declaration.
46const ICON_SOURCE_FILES = [
47 "index.html",
48 "public/index.html",
49 "app/routes/__root.tsx",
50 "src/routes/__root.tsx",
51 "app/root.tsx",
52 "src/root.tsx",
53 "src/index.html",
54] as const;
55
56// Matches <link ...> tags or object-like icon metadata where rel/href can appear in any order.
57const LINK_ICON_HTML_RE =
58 /<link\b(?=[^>]*\brel=["'](?:icon|shortcut icon)["'])(?=[^>]*\bhref=["']([^"'?]+))[^>]*>/i;
59const LINK_ICON_OBJ_RE =
60 /(?=[^}]*\brel\s*:\s*["'](?:icon|shortcut icon)["'])(?=[^}]*\bhref\s*:\s*["']([^"'?]+))[^}]*/i;
61
62export class ProjectFaviconResolutionError extends Schema.TaggedErrorClass<ProjectFaviconResolutionError>()(
63 "ProjectFaviconResolutionError",
64 {
65 operation: Schema.Literals([
66 "normalize-workspace",
67 "resolve-path",
68 "stat-candidate",
69 "read-source",
70 ]),
71 workspaceRoot: Schema.String,
72 relativePath: Schema.optional(Schema.String),
73 absolutePath: Schema.optional(Schema.String),
74 cause: Schema.Defect(),
75 },
76) {
77 override get message(): string {
78 return `Failed to resolve project favicon during ${this.operation} for workspace ${this.workspaceRoot}.`;
79 }
80}
81
82/** Service tag for project favicon resolution. */
83export class ProjectFaviconResolver extends Context.Service<
84 ProjectFaviconResolver,
85 {
86 /**
87 * Resolve a favicon or icon file path for the provided workspace root.
88 *
89 * Returns `null` when no candidate icon file can be found.
90 */
91 readonly resolvePath: (
92 cwd: string,
93 ) => Effect.Effect<string | null, ProjectFaviconResolutionError>;
94 }
95>()("v12/project/ProjectFaviconResolver") {}
96
97function extractIconHref(source: string): string | null {
98 const htmlMatch = source.match(LINK_ICON_HTML_RE);
99 if (htmlMatch?.[1]) return htmlMatch[1];
100 const objMatch = source.match(LINK_ICON_OBJ_RE);
101 if (objMatch?.[1]) return objMatch[1];
102 return null;
103}
104
105const optionOnNotFound = <A, R>(
106 effect: Effect.Effect<A, PlatformError.PlatformError, R>,
107): Effect.Effect<Option.Option<A>, PlatformError.PlatformError, R> =>
108 effect.pipe(
109 Effect.map(Option.some),
110 Effect.catchTags({
111 PlatformError: (error) =>
112 error.reason._tag === "NotFound" ? Effect.succeed(Option.none<A>()) : Effect.fail(error),
113 }),
114 );
115
116export const make = Effect.gen(function* () {
117 const fileSystem = yield* FileSystem.FileSystem;
118 const path = yield* Path.Path;
119 const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
120
121 const resolveIconHref = (href: string): ReadonlyArray<string> => {
122 const clean = href.replace(/^\//, "");
123 return [path.join("public", clean), clean];
124 };
125
126 const findExistingFile = Effect.fn("ProjectFaviconResolver.findExistingFile")(function* (
127 projectCwd: string,
128 relativeCandidates: ReadonlyArray<string>,
129 ): Effect.fn.Return<string | null, ProjectFaviconResolutionError> {
130 for (const relativePath of relativeCandidates) {
131 const candidate = yield* workspacePaths
132 .resolveRelativePathWithinRoot({
133 workspaceRoot: projectCwd,
134 relativePath,
135 })
136 .pipe(
137 Effect.map(Option.some),
138 Effect.catchTags({
139 WorkspacePathOutsideRootError: () =>
140 Effect.succeed(
141 Option.none<{ readonly absolutePath: string; readonly relativePath: string }>(),
142 ),
143 }),
144 );
145 if (Option.isNone(candidate)) {
146 continue;
147 }
148 const stats = yield* optionOnNotFound(fileSystem.stat(candidate.value.absolutePath)).pipe(
149 Effect.mapError(
150 (cause) =>
151 new ProjectFaviconResolutionError({
152 operation: "stat-candidate",
153 workspaceRoot: projectCwd,
154 relativePath,
155 absolutePath: candidate.value.absolutePath,
156 cause,
157 }),
158 ),
159 );
160 if (Option.isSome(stats) && stats.value.type === "File") {
161 return candidate.value.absolutePath;
162 }
163 }
164 return null;
165 });
166
167 const resolvePath: ProjectFaviconResolver["Service"]["resolvePath"] = Effect.fn(
168 "ProjectFaviconResolver.resolvePath",
169 )(function* (cwd) {
170 const projectCwd = yield* workspacePaths.normalizeWorkspaceRoot(cwd).pipe(
171 Effect.mapError(
172 (cause) =>
173 new ProjectFaviconResolutionError({
174 operation: "normalize-workspace",
175 workspaceRoot: cwd,
176 cause,
177 }),
178 ),
179 );
180 for (const candidate of FAVICON_CANDIDATES) {
181 const existing = yield* findExistingFile(projectCwd, [candidate]);
182 if (existing) {
183 return existing;
184 }
185 }
186
187 for (const sourceFile of ICON_SOURCE_FILES) {
188 const sourcePath = yield* workspacePaths
189 .resolveRelativePathWithinRoot({
190 workspaceRoot: projectCwd,
191 relativePath: sourceFile,
192 })
193 .pipe(
194 Effect.mapError(
195 (cause) =>
196 new ProjectFaviconResolutionError({
197 operation: "resolve-path",
198 workspaceRoot: projectCwd,
199 relativePath: sourceFile,
200 cause,
201 }),
202 ),
203 );
204 const source = yield* optionOnNotFound(
205 fileSystem.readFileString(sourcePath.absolutePath),
206 ).pipe(
207 Effect.mapError(
208 (cause) =>
209 new ProjectFaviconResolutionError({
210 operation: "read-source",
211 workspaceRoot: projectCwd,
212 relativePath: sourceFile,
213 absolutePath: sourcePath.absolutePath,
214 cause,
215 }),
216 ),
217 );
218 if (Option.isNone(source)) {
219 continue;
220 }
221 const href = extractIconHref(source.value);
222 if (!href) {
223 continue;
224 }
225 const existing = yield* findExistingFile(projectCwd, resolveIconHref(href));
226 if (existing) {
227 return existing;
228 }
229 }
230
231 return null;
232 });
233
234 return ProjectFaviconResolver.of({ resolvePath });
235});
236
237export const layer = Layer.effect(ProjectFaviconResolver, make);