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