Open History to see the last commit
1import * as Cache from "effect/Cache";
2import * as Cause from "effect/Cause";
3import * as Context from "effect/Context";
4import * as Duration from "effect/Duration";
5import * as Effect from "effect/Effect";
6import * as Exit from "effect/Exit";
7import * as Fiber from "effect/Fiber";
8import * as FileSystem from "effect/FileSystem";
9import * as Layer from "effect/Layer";
10import * as Option from "effect/Option";
11import * as Path from "effect/Path";
12import * as PlatformError from "effect/PlatformError";
13import * as Schema from "effect/Schema";
14
15import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
16import * as T3ProjectFileLoader from "./T3ProjectFileLoader.ts";
17
18const FAVICON_CACHE_CAPACITY = 512;
19const ICON_SOURCE_SCAN_BYTES = 128 * 1024;
20const FAVICON_POSITIVE_CACHE_TTL = Duration.minutes(10);
21const FAVICON_NEGATIVE_CACHE_TTL = Duration.minutes(1);
22
23function faviconCacheKey(cwd: string, faviconPath?: string): string {
24 return `${faviconPath ?? ""}\0${cwd}`;
25}
26
27function parseFaviconCacheKey(key: string): {
28 readonly cwd: string;
29 readonly faviconPath?: string;
30} {
31 const separatorIndex = key.indexOf("\0");
32 if (separatorIndex === -1) {
33 return { cwd: key };
34 }
35 const faviconPath = key.slice(0, separatorIndex);
36 const cwd = key.slice(separatorIndex + 1);
37 return faviconPath.length === 0 ? { cwd } : { cwd, faviconPath };
38}
39
40const FAVICON_CANDIDATES = [
41 "favicon.svg",
42 "favicon.ico",
43 "favicon.png",
44 "public/favicon.svg",
45 "public/favicon.ico",
46 "public/favicon.png",
47 "app/favicon.ico",
48 "app/favicon.png",
49 "app/icon.svg",
50 "app/icon.png",
51 "app/icon.ico",
52 "src/favicon.ico",
53 "src/favicon.svg",
54 "src/app/favicon.ico",
55 "src/app/icon.svg",
56 "src/app/icon.png",
57 "assets/icon.svg",
58 "assets/icon.png",
59 "assets/logo.svg",
60 "assets/logo.png",
61 ".idea/icon.svg",
62 "Resources/AppIcon.icns",
63 "AppIcon.icns",
64] as const;
65
66// Flutter's default favicon ranks below icons a project declares in its source.
67const FALLBACK_FAVICON_CANDIDATES = ["web/favicon.png"] as const;
68
69const ICON_SOURCE_FILES = [
70 "index.html",
71 "public/index.html",
72 "app/routes/__root.tsx",
73 "src/routes/__root.tsx",
74 "app/root.tsx",
75 "src/root.tsx",
76 "src/index.html",
77] as const;
78
79const HTML_LINK_RE = /<link\b[^<>]*>/gi;
80// `rel` is an unordered, whitespace-separated token list; any `icon` token marks an icon link.
81const ICON_REL_VALUE = String.raw`(?:"(?:[^"]*[\t\n\f\r ])?icon(?=[\t\n\f\r "])|'(?:[^']*[\t\n\f\r ])?icon(?=[\t\n\f\r ']))`;
82const HTML_ICON_REL_RE = new RegExp(String.raw`\brel=${ICON_REL_VALUE}`, "i");
83const HTML_ICON_HREF_RE = /\bhref=["']([^"'?]+)/i;
84const ICON_REL_RE = new RegExp(String.raw`\brel\s*:\s*${ICON_REL_VALUE}`, "i");
85const ICON_HREF_RE = /\bhref\s*:\s*["']([^"'?]+)/i;
86
87export class ProjectFaviconResolutionError extends Schema.TaggedError<ProjectFaviconResolutionError>()(
88 "ProjectFaviconResolutionError",
89 {
90 operation: Schema.Literals([
91 "normalize-workspace",
92 "resolve-path",
93 "stat-candidate",
94 "read-source",
95 ]),
96 workspaceRoot: Schema.String,
97 relativePath: Schema.optional(Schema.String),
98 absolutePath: Schema.optional(Schema.String),
99 cause: Schema.Defect(),
100 },
101) {
102 override get message(): string {
103 return `Failed to resolve project favicon during ${this.operation} for workspace ${this.workspaceRoot}.`;
104 }
105}
106
107const isWorkspaceRootNotExistsError = Schema.is(WorkspacePaths.WorkspaceRootNotExistsError);
108
109export const isMissingWorkspaceRoot = (error: ProjectFaviconResolutionError): boolean =>
110 error.operation === "normalize-workspace" && isWorkspaceRootNotExistsError(error.cause);
111
112export class ProjectFaviconResolver extends Context.Service<
113 ProjectFaviconResolver,
114 {
115 readonly resolvePath: (
116 cwd: string,
117 faviconPath?: string,
118 ) => Effect.Effect<string | null, ProjectFaviconResolutionError>;
119 /** Forgets cached lookups for a workspace whose files changed, such as a finished clone. */
120 readonly invalidate: (cwd: string) => Effect.Effect<void>;
121 }
122>()("t3/project/ProjectFaviconResolver") {}
123
124function extractIconHref(source: string): string | null {
125 for (const [tag] of source.matchAll(HTML_LINK_RE)) {
126 if (!HTML_ICON_REL_RE.test(tag)) continue;
127 const hrefMatch = tag.match(HTML_ICON_HREF_RE);
128 if (hrefMatch?.[1]) return hrefMatch[1];
129 }
130 for (const run of source.split("}")) {
131 if (!ICON_REL_RE.test(run)) continue;
132 const hrefMatch = run.match(ICON_HREF_RE);
133 if (hrefMatch?.[1]) return hrefMatch[1];
134 }
135 return null;
136}
137
138export const optionOnNotFound = <A, R>(
139 effect: Effect.Effect<A, PlatformError.PlatformError, R>,
140): Effect.Effect<Option.Option<A>, PlatformError.PlatformError, R> =>
141 effect.pipe(
142 Effect.asSome,
143 Effect.catchTags({
144 PlatformError: (error) =>
145 error.reason._tag === "NotFound" ? Effect.succeed(Option.none<A>()) : Effect.fail(error),
146 }),
147 );
148
149export const make = Effect.gen(function* () {
150 const fileSystem = yield* FileSystem.FileSystem;
151 const path = yield* Path.Path;
152 const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
153 const projectFileLoader = yield* T3ProjectFileLoader.T3ProjectFileLoader;
154
155 const resolveIconHref = (href: string): ReadonlyArray<string> => {
156 // Browsers strip surrounding whitespace from URL attributes; file paths keep theirs.
157 const clean = href.trim().replace(/^\//, "");
158 return [path.join("public", clean), clean];
159 };
160
161 const findExistingFile = Effect.fn("ProjectFaviconResolver.findExistingFile")(function* (
162 projectCwd: string,
163 relativeCandidates: ReadonlyArray<string>,
164 candidateScope: "workspace" | "filesystem",
165 ): Effect.fn.Return<string | null, ProjectFaviconResolutionError> {
166 for (const relativePath of relativeCandidates) {
167 const candidate = yield* (
168 candidateScope === "filesystem" && path.isAbsolute(relativePath)
169 ? Effect.succeed({ absolutePath: relativePath, relativePath })
170 : workspacePaths.resolveRelativePathWithinRoot({
171 workspaceRoot: projectCwd,
172 relativePath,
173 })
174 ).pipe(
175 Effect.asSome,
176 Effect.catchTags({
177 WorkspacePathOutsideRootError: () =>
178 Effect.succeed(
179 Option.none<{ readonly absolutePath: string; readonly relativePath: string }>(),
180 ),
181 }),
182 );
183 if (Option.isNone(candidate)) {
184 continue;
185 }
186 const stats = yield* optionOnNotFound(fileSystem.stat(candidate.value.absolutePath)).pipe(
187 Effect.mapError(
188 (cause) =>
189 new ProjectFaviconResolutionError({
190 operation: "stat-candidate",
191 workspaceRoot: projectCwd,
192 relativePath,
193 absolutePath: candidate.value.absolutePath,
194 cause,
195 }),
196 ),
197 );
198 if (Option.isSome(stats) && stats.value.type === "File") {
199 return candidate.value.absolutePath;
200 }
201 }
202 return null;
203 });
204
205 const findIconFromSource = Effect.fn("ProjectFaviconResolver.findIconFromSource")(function* (
206 projectCwd: string,
207 sourceFile: string,
208 ): Effect.fn.Return<string | null, ProjectFaviconResolutionError> {
209 const sourcePath = yield* workspacePaths
210 .resolveRelativePathWithinRoot({
211 workspaceRoot: projectCwd,
212 relativePath: sourceFile,
213 })
214 .pipe(
215 Effect.mapError(
216 (cause) =>
217 new ProjectFaviconResolutionError({
218 operation: "resolve-path",
219 workspaceRoot: projectCwd,
220 relativePath: sourceFile,
221 cause,
222 }),
223 ),
224 );
225 const stats = yield* optionOnNotFound(fileSystem.stat(sourcePath.absolutePath)).pipe(
226 Effect.mapError(
227 (cause) =>
228 new ProjectFaviconResolutionError({
229 operation: "stat-candidate",
230 workspaceRoot: projectCwd,
231 relativePath: sourceFile,
232 absolutePath: sourcePath.absolutePath,
233 cause,
234 }),
235 ),
236 );
237 if (Option.isNone(stats) || stats.value.type !== "File") {
238 return null;
239 }
240 const source = yield* optionOnNotFound(
241 fileSystem.open(sourcePath.absolutePath, { flag: "r" }).pipe(
242 Effect.flatMap((file) => file.readAlloc(ICON_SOURCE_SCAN_BYTES)),
243 Effect.scoped,
244 ),
245 ).pipe(
246 Effect.mapError(
247 (cause) =>
248 new ProjectFaviconResolutionError({
249 operation: "read-source",
250 workspaceRoot: projectCwd,
251 relativePath: sourceFile,
252 absolutePath: sourcePath.absolutePath,
253 cause,
254 }),
255 ),
256 );
257 if (Option.isNone(source) || Option.isNone(source.value)) {
258 return null;
259 }
260 const href = extractIconHref(new TextDecoder().decode(source.value.value));
261 if (!href) {
262 return null;
263 }
264 return yield* findExistingFile(projectCwd, resolveIconHref(href), "workspace");
265 });
266
267 // Probe concurrently but join in list order so lower-ranked probes cannot delay a hit.
268 // A failure surfaces only if no earlier probe found a file; scope exit interrupts remaining probes.
269 const firstInOrder = Effect.fn("ProjectFaviconResolver.firstInOrder")(function* <A>(
270 items: ReadonlyArray<A>,
271 probe: (item: A) => Effect.Effect<string | null, ProjectFaviconResolutionError>,
272 ) {
273 const fibers = yield* Effect.forEach(items, (item) => Effect.forkScoped(probe(item)));
274 for (const fiber of fibers) {
275 const found = yield* Fiber.join(fiber);
276 if (found) {
277 return found;
278 }
279 }
280 return null;
281 }, Effect.scoped);
282
283 const resolvePathUncached = Effect.fn("ProjectFaviconResolver.resolvePathUncached")(function* (
284 cwd: string,
285 faviconPath?: string,
286 ): Effect.fn.Return<string | null, ProjectFaviconResolutionError> {
287 const projectCwd = yield* workspacePaths.normalizeWorkspaceRoot(cwd).pipe(
288 Effect.mapError(
289 (cause) =>
290 new ProjectFaviconResolutionError({
291 operation: "normalize-workspace",
292 workspaceRoot: cwd,
293 cause,
294 }),
295 ),
296 );
297 if (faviconPath !== undefined) {
298 const existing = yield* findExistingFile(projectCwd, [faviconPath], "filesystem");
299 if (existing) {
300 return existing;
301 }
302 }
303
304 const projectFile = yield* projectFileLoader.load(projectCwd);
305 if (Option.isSome(projectFile) && projectFile.value.iconPath !== undefined) {
306 const existing = yield* findExistingFile(
307 projectCwd,
308 [projectFile.value.iconPath],
309 "workspace",
310 );
311 if (existing) {
312 return existing;
313 }
314 }
315
316 const wellKnown = yield* firstInOrder(FAVICON_CANDIDATES, (candidate) =>
317 findExistingFile(projectCwd, [candidate], "workspace"),
318 );
319 if (wellKnown) {
320 return wellKnown;
321 }
322
323 const sourceDeclared = yield* firstInOrder(ICON_SOURCE_FILES, (sourceFile) =>
324 findIconFromSource(projectCwd, sourceFile),
325 );
326 if (sourceDeclared) {
327 return sourceDeclared;
328 }
329
330 return yield* findExistingFile(projectCwd, FALLBACK_FAVICON_CANDIDATES, "workspace");
331 });
332
333 const faviconCache = yield* Cache.makeWith<string, string | null, ProjectFaviconResolutionError>(
334 (key) => {
335 const { cwd, faviconPath } = parseFaviconCacheKey(key);
336 return resolvePathUncached(cwd, faviconPath);
337 },
338 {
339 capacity: FAVICON_CACHE_CAPACITY,
340 timeToLive: Exit.match({
341 onSuccess: (value: string | null) =>
342 value === null ? FAVICON_NEGATIVE_CACHE_TTL : FAVICON_POSITIVE_CACHE_TTL,
343 onFailure: (cause) =>
344 Option.exists(Cause.findErrorOption(cause), isMissingWorkspaceRoot)
345 ? FAVICON_NEGATIVE_CACHE_TTL
346 : Duration.zero,
347 }),
348 },
349 );
350
351 const resolvePath: ProjectFaviconResolver["Service"]["resolvePath"] = Effect.fn(
352 "ProjectFaviconResolver.resolvePath",
353 )(function* (cwd, faviconPath) {
354 const key = faviconCacheKey(cwd, faviconPath);
355 const cached = yield* Cache.get(faviconCache, key);
356 if (cached === null) {
357 return null;
358 }
359
360 const stats = yield* optionOnNotFound(fileSystem.stat(cached)).pipe(
361 Effect.mapError(
362 (cause) =>
363 new ProjectFaviconResolutionError({
364 operation: "stat-candidate",
365 workspaceRoot: cwd,
366 absolutePath: cached,
367 cause,
368 }),
369 ),
370 );
371 if (Option.isSome(stats) && stats.value.type === "File") {
372 return cached;
373 }
374
375 yield* Cache.invalidate(faviconCache, key);
376 return yield* Cache.get(faviconCache, key);
377 });
378
379 const invalidate: ProjectFaviconResolver["Service"]["invalidate"] = (cwd) =>
380 Cache.keys(faviconCache).pipe(
381 Effect.flatMap((keys) =>
382 Effect.forEach(
383 Array.from(keys).filter((key) => parseFaviconCacheKey(key).cwd === cwd),
384 (key) => Cache.invalidate(faviconCache, key),
385 { discard: true },
386 ),
387 ),
388 );
389
390 return ProjectFaviconResolver.of({ resolvePath, invalidate });
391});
392
393export const layer = Layer.effect(ProjectFaviconResolver, make);