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