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.
58// The tag pattern is anchored on `<link`, so it only starts at real candidates. Object metadata
59// is matched by scanning brace-free runs instead of by one combined pattern: an unanchored
60// pattern restarts at every offset and rescans forward, which is quadratic on large sources.
61const LINK_ICON_HTML_RE =
62 /<link\b(?=[^>]*\brel=["'](?:icon|shortcut icon)["'])(?=[^>]*\bhref=["']([^"'?]+))[^>]*>/i;
63const ICON_REL_RE = /\brel\s*:\s*["'](?:icon|shortcut icon)["']/i;
64const ICON_HREF_RE = /\bhref\s*:\s*["']([^"'?]+)/i;
65
66export class ProjectFaviconResolutionError extends Schema.TaggedErrorClass<ProjectFaviconResolutionError>()(
67 "ProjectFaviconResolutionError",
68 {
69 operation: Schema.Literals([
70 "normalize-workspace",
71 "resolve-path",
72 "stat-candidate",
73 "read-source",
74 ]),
75 workspaceRoot: Schema.String,
76 relativePath: Schema.optional(Schema.String),
77 absolutePath: Schema.optional(Schema.String),
78 cause: Schema.Defect(),
79 },
80) {
81 override get message(): string {
82 return `Failed to resolve project favicon during ${this.operation} for workspace ${this.workspaceRoot}.`;
83 }
84}
85
86/** Service tag for project favicon resolution. */
87export class ProjectFaviconResolver extends Context.Service<
88 ProjectFaviconResolver,
89 {
90 /**
91 * Resolve a favicon or icon file path for the provided workspace root.
92 *
93 * Returns `null` when no candidate icon file can be found.
94 */
95 readonly resolvePath: (
96 cwd: string,
97 faviconPath?: string,
98 ) => Effect.Effect<string | null, ProjectFaviconResolutionError>;
99 }
100>()("t3/project/ProjectFaviconResolver") {}
101
102function extractIconHref(source: string): string | null {
103 const htmlMatch = source.match(LINK_ICON_HTML_RE);
104 if (htmlMatch?.[1]) return htmlMatch[1];
105 // Icon metadata counts when `rel` and `href` share a brace-free run, so a run holding `rel`
106 // but no href falls through to the next one rather than ending the search.
107 for (const run of source.split("}")) {
108 if (!ICON_REL_RE.test(run)) continue;
109 const hrefMatch = run.match(ICON_HREF_RE);
110 if (hrefMatch?.[1]) return hrefMatch[1];
111 }
112 return null;
113}
114
115const optionOnNotFound = <A, R>(
116 effect: Effect.Effect<A, PlatformError.PlatformError, R>,
117): Effect.Effect<Option.Option<A>, PlatformError.PlatformError, R> =>
118 effect.pipe(
119 Effect.map(Option.some),
120 Effect.catchTags({
121 PlatformError: (error) =>
122 error.reason._tag === "NotFound" ? Effect.succeed(Option.none<A>()) : Effect.fail(error),
123 }),
124 );
125
126export const make = Effect.gen(function* () {
127 const fileSystem = yield* FileSystem.FileSystem;
128 const path = yield* Path.Path;
129 const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
130 const projectFileLoader = yield* T3ProjectFileLoader.T3ProjectFileLoader;
131
132 const resolveIconHref = (href: string): ReadonlyArray<string> => {
133 const clean = href.replace(/^\//, "");
134 return [path.join("public", clean), clean];
135 };
136
137 const findExistingFile = Effect.fn("ProjectFaviconResolver.findExistingFile")(function* (
138 projectCwd: string,
139 relativeCandidates: ReadonlyArray<string>,
140 candidateScope: "workspace" | "filesystem",
141 ): Effect.fn.Return<string | null, ProjectFaviconResolutionError> {
142 for (const relativePath of relativeCandidates) {
143 const candidate = yield* (
144 candidateScope === "filesystem" && path.isAbsolute(relativePath)
145 ? Effect.succeed({ absolutePath: relativePath, relativePath })
146 : workspacePaths.resolveRelativePathWithinRoot({
147 workspaceRoot: projectCwd,
148 relativePath,
149 })
150 ).pipe(
151 Effect.map(Option.some),
152 Effect.catchTags({
153 WorkspacePathOutsideRootError: () =>
154 Effect.succeed(
155 Option.none<{ readonly absolutePath: string; readonly relativePath: string }>(),
156 ),
157 }),
158 );
159 if (Option.isNone(candidate)) {
160 continue;
161 }
162 const stats = yield* optionOnNotFound(fileSystem.stat(candidate.value.absolutePath)).pipe(
163 Effect.mapError(
164 (cause) =>
165 new ProjectFaviconResolutionError({
166 operation: "stat-candidate",
167 workspaceRoot: projectCwd,
168 relativePath,
169 absolutePath: candidate.value.absolutePath,
170 cause,
171 }),
172 ),
173 );
174 if (Option.isSome(stats) && stats.value.type === "File") {
175 return candidate.value.absolutePath;
176 }
177 }
178 return null;
179 });
180
181 const resolvePath: ProjectFaviconResolver["Service"]["resolvePath"] = Effect.fn(
182 "ProjectFaviconResolver.resolvePath",
183 )(function* (cwd, faviconPath) {
184 const projectCwd = yield* workspacePaths.normalizeWorkspaceRoot(cwd).pipe(
185 Effect.mapError(
186 (cause) =>
187 new ProjectFaviconResolutionError({
188 operation: "normalize-workspace",
189 workspaceRoot: cwd,
190 cause,
191 }),
192 ),
193 );
194 // A grouped project's saved path can be absent from one checkout. Use it
195 // where it exists and retain automatic discovery for the other checkouts.
196 if (faviconPath !== undefined) {
197 const existing = yield* findExistingFile(projectCwd, [faviconPath], "filesystem");
198 if (existing) {
199 return existing;
200 }
201 }
202
203 // A t3.json iconPath takes precedence over the well-known locations.
204 const projectFile = yield* projectFileLoader.load(projectCwd);
205 if (Option.isSome(projectFile) && projectFile.value.iconPath !== undefined) {
206 const existing = yield* findExistingFile(
207 projectCwd,
208 [projectFile.value.iconPath],
209 "workspace",
210 );
211 if (existing) {
212 return existing;
213 }
214 }
215
216 for (const candidate of FAVICON_CANDIDATES) {
217 const existing = yield* findExistingFile(projectCwd, [candidate], "workspace");
218 if (existing) {
219 return existing;
220 }
221 }
222
223 for (const sourceFile of ICON_SOURCE_FILES) {
224 const sourcePath = yield* workspacePaths
225 .resolveRelativePathWithinRoot({
226 workspaceRoot: projectCwd,
227 relativePath: sourceFile,
228 })
229 .pipe(
230 Effect.mapError(
231 (cause) =>
232 new ProjectFaviconResolutionError({
233 operation: "resolve-path",
234 workspaceRoot: projectCwd,
235 relativePath: sourceFile,
236 cause,
237 }),
238 ),
239 );
240 const source = yield* optionOnNotFound(
241 fileSystem.readFileString(sourcePath.absolutePath),
242 ).pipe(
243 Effect.mapError(
244 (cause) =>
245 new ProjectFaviconResolutionError({
246 operation: "read-source",
247 workspaceRoot: projectCwd,
248 relativePath: sourceFile,
249 absolutePath: sourcePath.absolutePath,
250 cause,
251 }),
252 ),
253 );
254 if (Option.isNone(source)) {
255 continue;
256 }
257 const href = extractIconHref(source.value);
258 if (!href) {
259 continue;
260 }
261 const existing = yield* findExistingFile(projectCwd, resolveIconHref(href), "workspace");
262 if (existing) {
263 return existing;
264 }
265 }
266
267 return null;
268 });
269
270 return ProjectFaviconResolver.of({ resolvePath });
271});
272
273export const layer = Layer.effect(ProjectFaviconResolver, make);