Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ProjectFaviconResolver.ts

375 lines12.7 KB

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 Cache from "effect/Cache";
10import * as Context from "effect/Context";
11import * as Duration from "effect/Duration";
12import * as Effect from "effect/Effect";
13import * as Exit from "effect/Exit";
14import * as Fiber from "effect/Fiber";
15import * as FileSystem from "effect/FileSystem";
16import * as Layer from "effect/Layer";
17import * as Option from "effect/Option";
18import * as Path from "effect/Path";
19import * as PlatformError from "effect/PlatformError";
20import * as Schema from "effect/Schema";
21​
22import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
23import * as T3ProjectFileLoader from "./T3ProjectFileLoader.ts";
24​
25// Resolution probes 21 well-known paths plus 7 source files, so a miss
26// costs ~30 filesystem probes. AssetAccess resolves on every project-favicon
27// asset URL, and a project's icon does not move, so the answer is cached.
28const FAVICON_CACHE_CAPACITY = 512;
29const FAVICON_POSITIVE_CACHE_TTL = Duration.minutes(10);
30const FAVICON_NEGATIVE_CACHE_TTL = Duration.minutes(1);
31​
32function faviconCacheKey(cwd: string, faviconPath?: string): string {
33 return `${faviconPath ?? ""}\0${cwd}`;
35​
36function parseFaviconCacheKey(key: string): {
37 readonly cwd: string;
38 readonly faviconPath?: string;
39} {
40 const separatorIndex = key.indexOf("\0");
41 if (separatorIndex === -1) {
42 return { cwd: key };
43 }
44 const faviconPath = key.slice(0, separatorIndex);
45 const cwd = key.slice(separatorIndex + 1);
46 return faviconPath.length === 0 ? { cwd } : { cwd, faviconPath };
48​
49// Well-known favicon paths checked in order.
50const FAVICON_CANDIDATES = [
51 "favicon.svg",
52 "favicon.ico",
53 "favicon.png",
54 "public/favicon.svg",
55 "public/favicon.ico",
56 "public/favicon.png",
57 "app/favicon.ico",
58 "app/favicon.png",
59 "app/icon.svg",
60 "app/icon.png",
61 "app/icon.ico",
62 "src/favicon.ico",
63 "src/favicon.svg",
64 "src/app/favicon.ico",
65 "src/app/icon.svg",
66 "src/app/icon.png",
67 "assets/icon.svg",
68 "assets/icon.png",
69 "assets/logo.svg",
70 "assets/logo.png",
71 ".idea/icon.svg",
72] as const;
73​
74// Files that may contain a <link rel="icon"> or icon metadata declaration.
75const ICON_SOURCE_FILES = [
76 "index.html",
77 "public/index.html",
78 "app/routes/__root.tsx",
79 "src/routes/__root.tsx",
80 "app/root.tsx",
81 "src/root.tsx",
82 "src/index.html",
83] as const;
84​
85// Matches <link ...> tags or object-like icon metadata where rel/href can appear in any order.
86// The tag pattern is anchored on `<link`, so it only starts at real candidates. Object metadata
87// is matched by scanning brace-free runs instead of by one combined pattern: an unanchored
88// pattern restarts at every offset and rescans forward, which is quadratic on large sources.
89const LINK_ICON_HTML_RE =
90 /<link\b(?=[^>]*\brel=["'](?:icon|shortcut icon)["'])(?=[^>]*\bhref=["']([^"'?]+))[^>]*>/i;
91const ICON_REL_RE = /\brel\s*:\s*["'](?:icon|shortcut icon)["']/i;
92const ICON_HREF_RE = /\bhref\s*:\s*["']([^"'?]+)/i;
93​
94export class ProjectFaviconResolutionError extends Schema.TaggedError<ProjectFaviconResolutionError>()(
95 "ProjectFaviconResolutionError",
96 {
97 operation: Schema.Literals([
98 "normalize-workspace",
99 "resolve-path",
100 "stat-candidate",
101 "read-source",
102 ]),
103 workspaceRoot: Schema.String,
104 relativePath: Schema.optional(Schema.String),
105 absolutePath: Schema.optional(Schema.String),
106 cause: Schema.Defect(),
107 },
108) {
109 override get message(): string {
110 return `Failed to resolve project favicon during ${this.operation} for workspace ${this.workspaceRoot}.`;
111 }
113​
114const isWorkspaceRootNotExistsError = Schema.is(WorkspacePaths.WorkspaceRootNotExistsError);
115​
116/** True when the workspace root itself is gone, e.g. a moved or deleted checkout. */
117export const isMissingWorkspaceRoot = (error: ProjectFaviconResolutionError): boolean =>
118 error.operation === "normalize-workspace" && isWorkspaceRootNotExistsError(error.cause);
119​
120/** Service tag for project favicon resolution. */
121export class ProjectFaviconResolver extends Context.Service<
122 ProjectFaviconResolver,
123 {
124 /**
125 * Resolve a favicon or icon file path for the provided workspace root.
126 *
127 * Returns `null` when no candidate icon file can be found.
128 */
129 readonly resolvePath: (
130 cwd: string,
131 faviconPath?: string,
132 ) => Effect.Effect<string | null, ProjectFaviconResolutionError>;
133 }
134>()("t3/project/ProjectFaviconResolver") {}
135​
136function extractIconHref(source: string): string | null {
137 const htmlMatch = source.match(LINK_ICON_HTML_RE);
138 if (htmlMatch?.[1]) return htmlMatch[1];
139 // Icon metadata counts when `rel` and `href` share a brace-free run, so a run holding `rel`
140 // but no href falls through to the next one rather than ending the search.
141 for (const run of source.split("}")) {
142 if (!ICON_REL_RE.test(run)) continue;
143 const hrefMatch = run.match(ICON_HREF_RE);
144 if (hrefMatch?.[1]) return hrefMatch[1];
145 }
146 return null;
148​
149const optionOnNotFound = <A, R>(
150 effect: Effect.Effect<A, PlatformError.PlatformError, R>,
151): Effect.Effect<Option.Option<A>, PlatformError.PlatformError, R> =>
152 effect.pipe(
153 Effect.asSome,
154 Effect.catchTags({
155 PlatformError: (error) =>
156 error.reason._tag === "NotFound" ? Effect.succeed(Option.none<A>()) : Effect.fail(error),
157 }),
158 );
159​
160export const make = Effect.gen(function* () {
161 const fileSystem = yield* FileSystem.FileSystem;
162 const path = yield* Path.Path;
163 const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
164 const projectFileLoader = yield* T3ProjectFileLoader.T3ProjectFileLoader;
165​
166 const resolveIconHref = (href: string): ReadonlyArray<string> => {
167 const clean = href.replace(/^\//, "");
168 return [path.join("public", clean), clean];
169 };
170​
171 const findExistingFile = Effect.fn("ProjectFaviconResolver.findExistingFile")(function* (
172 projectCwd: string,
173 relativeCandidates: ReadonlyArray<string>,
174 candidateScope: "workspace" | "filesystem",
175 ): Effect.fn.Return<string | null, ProjectFaviconResolutionError> {
176 for (const relativePath of relativeCandidates) {
177 const candidate = yield* (
178 candidateScope === "filesystem" && path.isAbsolute(relativePath)
179 ? Effect.succeed({ absolutePath: relativePath, relativePath })
180 : workspacePaths.resolveRelativePathWithinRoot({
181 workspaceRoot: projectCwd,
182 relativePath,
183 })
184 ).pipe(
185 Effect.asSome,
186 Effect.catchTags({
187 WorkspacePathOutsideRootError: () =>
188 Effect.succeed(
189 Option.none<{ readonly absolutePath: string; readonly relativePath: string }>(),
190 ),
191 }),
192 );
193 if (Option.isNone(candidate)) {
194 continue;
195 }
196 const stats = yield* optionOnNotFound(fileSystem.stat(candidate.value.absolutePath)).pipe(
197 Effect.mapError(
198 (cause) =>
199 new ProjectFaviconResolutionError({
200 operation: "stat-candidate",
201 workspaceRoot: projectCwd,
202 relativePath,
203 absolutePath: candidate.value.absolutePath,
204 cause,
205 }),
206 ),
207 );
208 if (Option.isSome(stats) && stats.value.type === "File") {
209 return candidate.value.absolutePath;
210 }
211 }
212 return null;
213 });
214​
215 // Reads one source file and resolves the icon it declares, if any.
216 const findIconFromSource = Effect.fn("ProjectFaviconResolver.findIconFromSource")(function* (
217 projectCwd: string,
218 sourceFile: string,
219 ): Effect.fn.Return<string | null, ProjectFaviconResolutionError> {
220 const sourcePath = yield* workspacePaths
221 .resolveRelativePathWithinRoot({
222 workspaceRoot: projectCwd,
223 relativePath: sourceFile,
224 })
225 .pipe(
226 Effect.mapError(
227 (cause) =>
228 new ProjectFaviconResolutionError({
229 operation: "resolve-path",
230 workspaceRoot: projectCwd,
231 relativePath: sourceFile,
232 cause,
233 }),
234 ),
235 );
236 const source = yield* optionOnNotFound(fileSystem.readFileString(sourcePath.absolutePath)).pipe(
237 Effect.mapError(
238 (cause) =>
239 new ProjectFaviconResolutionError({
240 operation: "read-source",
241 workspaceRoot: projectCwd,
242 relativePath: sourceFile,
243 absolutePath: sourcePath.absolutePath,
244 cause,
245 }),
246 ),
247 );
248 if (Option.isNone(source)) {
249 return null;
250 }
251 const href = extractIconHref(source.value);
252 if (!href) {
253 return null;
254 }
255 return yield* findExistingFile(projectCwd, resolveIconHref(href), "workspace");
256 });
257​
258 // Starts every probe at once and returns the first hit in list order. A miss
259 // costs one round of filesystem latency instead of one per probe, which
260 // matters when the disk is slow. Fibers are joined in order, so a hit returns
261 // without waiting for lower-ranked probes (the scope interrupts them), and a
262 // failure surfaces only when no earlier probe found a file.
263 const firstInOrder = <A>(
264 items: ReadonlyArray<A>,
265 probe: (item: A) => Effect.Effect<string | null, ProjectFaviconResolutionError>,
266 ) =>
267 Effect.gen(function* () {
268 const fibers = yield* Effect.forEach(items, (item) => Effect.forkScoped(probe(item)));
269 for (const fiber of fibers) {
270 const found = yield* Fiber.join(fiber);
271 if (found) {
272 return found;
273 }
274 }
275 return null;
276 }).pipe(Effect.scoped);
277​
278 const resolvePathUncached = Effect.fn("ProjectFaviconResolver.resolvePathUncached")(function* (
279 cwd: string,
280 faviconPath?: string,
281 ): Effect.fn.Return<string | null, ProjectFaviconResolutionError> {
282 const projectCwd = yield* workspacePaths.normalizeWorkspaceRoot(cwd).pipe(
283 Effect.mapError(
284 (cause) =>
285 new ProjectFaviconResolutionError({
286 operation: "normalize-workspace",
287 workspaceRoot: cwd,
288 cause,
289 }),
290 ),
291 );
292 // A grouped project's saved path can be absent from one checkout. Use it
293 // where it exists and retain automatic discovery for the other checkouts.
294 if (faviconPath !== undefined) {
295 const existing = yield* findExistingFile(projectCwd, [faviconPath], "filesystem");
296 if (existing) {
297 return existing;
298 }
299 }
300​
301 // A t3.json iconPath takes precedence over the well-known locations.
302 const projectFile = yield* projectFileLoader.load(projectCwd);
303 if (Option.isSome(projectFile) && projectFile.value.iconPath !== undefined) {
304 const existing = yield* findExistingFile(
305 projectCwd,
306 [projectFile.value.iconPath],
307 "workspace",
308 );
309 if (existing) {
310 return existing;
311 }
312 }
313​
314 const wellKnown = yield* firstInOrder(FAVICON_CANDIDATES, (candidate) =>
315 findExistingFile(projectCwd, [candidate], "workspace"),
316 );
317 if (wellKnown) {
318 return wellKnown;
319 }
320​
321 return yield* firstInOrder(ICON_SOURCE_FILES, (sourceFile) =>
322 findIconFromSource(projectCwd, sourceFile),
323 );
324 });
325​
326 const faviconCache = yield* Cache.makeWith<string, string | null, ProjectFaviconResolutionError>(
327 (key) => {
328 const { cwd, faviconPath } = parseFaviconCacheKey(key);
329 return resolvePathUncached(cwd, faviconPath);
330 },
331 {
332 capacity: FAVICON_CACHE_CAPACITY,
333 timeToLive: Exit.match({
334 onSuccess: (value: string | null) =>
335 value === null ? FAVICON_NEGATIVE_CACHE_TTL : FAVICON_POSITIVE_CACHE_TTL,
336 onFailure: () => Duration.zero,
337 }),
338 },
339 );
340​
341 const resolvePath: ProjectFaviconResolver["Service"]["resolvePath"] = Effect.fn(
342 "ProjectFaviconResolver.resolvePath",
343 )(function* (cwd, faviconPath) {
344 const key = faviconCacheKey(cwd, faviconPath);
345 const cached = yield* Cache.get(faviconCache, key);
346 if (cached === null) {
347 return null;
348 }
349​
350 // A hit still confirms the file with one stat rather than the ~20 probes a
351 // full walk costs, so a deleted icon falls back at once instead of after
352 // the TTL.
353 const stats = yield* optionOnNotFound(fileSystem.stat(cached)).pipe(
354 Effect.mapError(
355 (cause) =>
356 new ProjectFaviconResolutionError({
357 operation: "stat-candidate",
358 workspaceRoot: cwd,
359 absolutePath: cached,
360 cause,
361 }),
362 ),
363 );
364 if (Option.isSome(stats) && stats.value.type === "File") {
365 return cached;
366 }
367​
368 yield* Cache.invalidate(faviconCache, key);
369 return yield* Cache.get(faviconCache, key);
370 });
371​
372 return ProjectFaviconResolver.of({ resolvePath });
373});
374​
375export const layer = Layer.effect(ProjectFaviconResolver, make);