Open History to see the last commit
1import { safeDecodeURIComponent } from "@t3tools/shared/markdownLinks";
2import { characterEntities } from "character-entities";
3import { characterEntitiesLegacy } from "character-entities-legacy";
4import * as Cache from "effect/Cache";
5import * as Cause from "effect/Cause";
6import * as Context from "effect/Context";
7import * as Duration from "effect/Duration";
8import * as Effect from "effect/Effect";
9import * as Exit from "effect/Exit";
10import * as Fiber from "effect/Fiber";
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
21const FAVICON_CACHE_CAPACITY = 512;
22const ICON_SOURCE_SCAN_BYTES = 128 * 1024;
23const FAVICON_POSITIVE_CACHE_TTL = Duration.minutes(10);
24const FAVICON_NEGATIVE_CACHE_TTL = Duration.minutes(1);
25
26function faviconCacheKey(cwd: string, faviconPath?: string): string {
27 return `${faviconPath ?? ""}\0${cwd}`;
28}
29
30function parseFaviconCacheKey(key: string): {
31 readonly cwd: string;
32 readonly faviconPath?: string;
33} {
34 const separatorIndex = key.indexOf("\0");
35 if (separatorIndex === -1) {
36 return { cwd: key };
37 }
38 const faviconPath = key.slice(0, separatorIndex);
39 const cwd = key.slice(separatorIndex + 1);
40 return faviconPath.length === 0 ? { cwd } : { cwd, faviconPath };
41}
42
43const FAVICON_CANDIDATES = [
44 "favicon.svg",
45 "favicon.ico",
46 "favicon.png",
47 "public/favicon.svg",
48 "public/favicon.ico",
49 "public/favicon.png",
50 "app/favicon.ico",
51 "app/favicon.png",
52 "app/icon.svg",
53 "app/icon.png",
54 "app/icon.ico",
55 "src/favicon.ico",
56 "src/favicon.svg",
57 "src/app/favicon.ico",
58 "src/app/icon.svg",
59 "src/app/icon.png",
60 "assets/icon.svg",
61 "assets/icon.png",
62 "assets/logo.svg",
63 "assets/logo.png",
64 ".idea/icon.svg",
65 "Resources/AppIcon.icns",
66 "AppIcon.icns",
67] as const;
68
69// Flutter's default favicon ranks below icons a project declares in its source.
70const FALLBACK_FAVICON_CANDIDATES = ["web/favicon.png"] as const;
71
72const ICON_SOURCE_FILES = [
73 "index.html",
74 "public/index.html",
75 "app/routes/__root.tsx",
76 "src/routes/__root.tsx",
77 "app/root.tsx",
78 "src/root.tsx",
79 "src/index.html",
80] as const;
81
82// A quote opens a value only right after `=`; the lookahead+backreference keeps it atomic so
83// backtracking cannot re-read the value as plain text.
84// A comment (to `-->`, `--!>` or the end) hides the links inside it, as in a browser.
85const HTML_LINK_RE =
86 /<!--(?:-?>|[\s\S]*?--!?>|[\s\S]*)|<link\b(?:[^<>=]|=(?=([\t\n\f\r ]*(?:"[^"]*"|'[^']*')|))\1)*>/gi;
87// `rel` is an unordered, whitespace-separated token list; any `icon` token marks an icon link.
88const ICON_REL_VALUE = String.raw`(?:"(?:[^"]*[\t\n\f\r ])?icon(?=[\t\n\f\r "])|'(?:[^']*[\t\n\f\r ])?icon(?=[\t\n\f\r ']))`;
89// HTML attribute syntax: a name, then an optional double-quoted, single-quoted, or unquoted value.
90const HTML_ATTRIBUTE_RE =
91 /([^\t\n\f\r "'<>/=]+)(?:[\t\n\f\r ]*=[\t\n\f\r ]*(?:"([^"]*)"|'([^']*)'|([^\t\n\f\r >]+)))?/g;
92const ICON_REL_RE = new RegExp(
93 String.raw`(?:^|[\s,{]|\*\/)(?:"rel"|'rel'|rel)\s*:\s*${ICON_REL_VALUE}`,
94 "i",
95);
96const ICON_HREF_RE =
97 /(?:^|[\s,{]|\*\/)(?:"href"|'href'|href)\s*:\s*(["'])((?:\\[^?#]|(?!\1)[^\\?#])+)/i;
98// https://html.spec.whatwg.org/multipage/parsing.html#numeric-character-reference-end-state
99const HTML_C1_REPLACEMENTS: Readonly<Partial<Record<number, number>>> = {
100 0x80: 0x20ac,
101 0x82: 0x201a,
102 0x83: 0x0192,
103 0x84: 0x201e,
104 0x85: 0x2026,
105 0x86: 0x2020,
106 0x87: 0x2021,
107 0x88: 0x02c6,
108 0x89: 0x2030,
109 0x8a: 0x0160,
110 0x8b: 0x2039,
111 0x8c: 0x0152,
112 0x8e: 0x017d,
113 0x91: 0x2018,
114 0x92: 0x2019,
115 0x93: 0x201c,
116 0x94: 0x201d,
117 0x95: 0x2022,
118 0x96: 0x2013,
119 0x97: 0x2014,
120 0x98: 0x02dc,
121 0x99: 0x2122,
122 0x9a: 0x0161,
123 0x9b: 0x203a,
124 0x9c: 0x0153,
125 0x9e: 0x017e,
126 0x9f: 0x0178,
127};
128
129export class ProjectFaviconResolutionError extends Schema.TaggedError<ProjectFaviconResolutionError>()(
130 "ProjectFaviconResolutionError",
131 {
132 operation: Schema.Literals([
133 "normalize-workspace",
134 "resolve-path",
135 "stat-candidate",
136 "read-source",
137 ]),
138 workspaceRoot: Schema.String,
139 relativePath: Schema.optional(Schema.String),
140 absolutePath: Schema.optional(Schema.String),
141 cause: Schema.Defect(),
142 },
143) {
144 override get message(): string {
145 return `Failed to resolve project favicon during ${this.operation} for workspace ${this.workspaceRoot}.`;
146 }
147}
148
149const isWorkspaceRootNotExistsError = Schema.is(WorkspacePaths.WorkspaceRootNotExistsError);
150
151export const isMissingWorkspaceRoot = (error: ProjectFaviconResolutionError): boolean =>
152 error.operation === "normalize-workspace" && isWorkspaceRootNotExistsError(error.cause);
153
154export class ProjectFaviconResolver extends Context.Service<
155 ProjectFaviconResolver,
156 {
157 readonly resolvePath: (
158 cwd: string,
159 faviconPath?: string,
160 ) => Effect.Effect<string | null, ProjectFaviconResolutionError>;
161 /** Forgets cached lookups for a workspace whose files changed, such as a finished clone. */
162 readonly invalidate: (cwd: string) => Effect.Effect<void>;
163 }
164>()("t3/project/ProjectFaviconResolver") {}
165
166export function decodeHtmlAttribute(value: string, html: boolean): string {
167 return value.replace(
168 /&(?:([a-z][a-z\d]*)([;=]?)|#(?:(\d+)|x([a-f\d]+));?)/gi,
169 (reference, name?: string, terminator?: string, decimal?: string, hex?: string) => {
170 if (name !== undefined) {
171 // HTML attributes, unlike JSX, decode legacy names without `;` unless `=` or an alphanumeric follows.
172 const decoded =
173 terminator === ";"
174 ? Object.hasOwn(characterEntities, name)
175 : terminator === "" && html && characterEntitiesLegacy.includes(name);
176 return decoded ? characterEntities[name]! : reference;
177 }
178 const codePoint = hex === undefined ? Number(decimal) : Number.parseInt(hex, 16);
179 if (codePoint === 0 || codePoint > 0x10ffff || (codePoint >= 0xd800 && codePoint <= 0xdfff)) {
180 return "\uFFFD";
181 }
182 return String.fromCodePoint(HTML_C1_REPLACEMENTS[codePoint] ?? codePoint);
183 },
184 );
185}
186
187function* extractIconHrefs(source: string, html: boolean): Generator<string> {
188 for (const [tag] of source.matchAll(HTML_LINK_RE)) {
189 if (tag.startsWith("<!--")) continue;
190 const attributes = new Map<string, { value: string; quoted: boolean }>();
191 for (const [, name, doubleQuoted, singleQuoted, unquoted] of tag
192 .slice("<link".length)
193 .matchAll(HTML_ATTRIBUTE_RE)) {
194 const key = name!.toLowerCase();
195 if (attributes.has(key)) continue;
196 const quotedValue = doubleQuoted ?? singleQuoted;
197 attributes.set(key, {
198 value: quotedValue ?? unquoted ?? "",
199 quoted: quotedValue !== undefined,
200 });
201 }
202 const rawRel = attributes.get("rel")?.value;
203 if (rawRel === undefined) continue;
204 const rel = (html ? decodeHtmlAttribute(rawRel, true) : rawRel)
205 .toLowerCase()
206 .split(/[\t\n\f\r ]+/);
207 if (!rel.includes("icon")) continue;
208 const href = attributes.get("href");
209 // An unquoted `{...}` is a JSX expression, not a path.
210 if (!href || (!href.quoted && href.value.startsWith("{"))) continue;
211 const path = decodeHtmlAttribute(href.value, html).split(/[?#]/, 1)[0];
212 if (path) yield path;
213 }
214 for (const run of source.split("}")) {
215 if (!ICON_REL_RE.test(run)) continue;
216 const [, quote, href] = run.match(ICON_HREF_RE) ?? [];
217 if (href) {
218 yield href.replace(/\\([\s\S])/g, (escape, character: string) =>
219 character === quote ? character : escape,
220 );
221 }
222 }
223}
224
225export const optionOnNotFound = <A, R>(
226 effect: Effect.Effect<A, PlatformError.PlatformError, R>,
227): Effect.Effect<Option.Option<A>, PlatformError.PlatformError, R> =>
228 effect.pipe(
229 Effect.asSome,
230 Effect.catchTags({
231 PlatformError: (error) =>
232 error.reason._tag === "NotFound" ? Effect.succeed(Option.none<A>()) : Effect.fail(error),
233 }),
234 );
235
236// A path through a file (ENOTDIR) or a symlink loop names no file either.
237const optionOnMissing = <A, R>(
238 effect: Effect.Effect<A, PlatformError.PlatformError, R>,
239): Effect.Effect<Option.Option<A>, PlatformError.PlatformError, R> =>
240 optionOnNotFound(effect).pipe(
241 Effect.catchIf(
242 (error) => error.reason._tag === "BadResource",
243 () => Effect.succeedNone,
244 ),
245 );
246
247export const make = Effect.gen(function* () {
248 const fileSystem = yield* FileSystem.FileSystem;
249 const path = yield* Path.Path;
250 const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
251 const projectFileLoader = yield* T3ProjectFileLoader.T3ProjectFileLoader;
252
253 const resolveIconHref = (href: string, sourceFile: string): ReadonlyArray<string> => {
254 // `data:`, `https:` and `//host` icons name no project file, and a long data URL fails `stat`.
255 if (/^(?:[a-z][a-z\d+.-]*:|\/\/)/i.test(href.trim())) return [];
256 // Browsers strip surrounding whitespace from URL attributes; file paths keep theirs.
257 const clean = safeDecodeURIComponent(href.trim().replace(/^\//, ""));
258 // A decoded NUL fails `stat` instead of missing.
259 if (clean.includes("\0")) return [];
260 const candidates = [path.join("public", clean), clean];
261 // A relative href in HTML resolves against that file's directory (e.g. Vite `root: "src"`).
262 const htmlDir = sourceFile.endsWith(".html") ? path.dirname(sourceFile) : ".";
263 if (htmlDir !== "." && !href.trim().startsWith("/")) {
264 candidates.push(path.join(htmlDir, clean));
265 }
266 return candidates;
267 };
268
269 const findExistingFile = Effect.fn("ProjectFaviconResolver.findExistingFile")(function* (
270 projectCwd: string,
271 relativeCandidates: ReadonlyArray<string>,
272 candidateScope: "workspace" | "filesystem",
273 ): Effect.fn.Return<string | null, ProjectFaviconResolutionError> {
274 for (const relativePath of relativeCandidates) {
275 const candidate = yield* (
276 candidateScope === "filesystem" && path.isAbsolute(relativePath)
277 ? Effect.succeed({ absolutePath: relativePath, relativePath })
278 : workspacePaths.resolveRelativePathWithinRoot({
279 workspaceRoot: projectCwd,
280 relativePath,
281 })
282 ).pipe(
283 Effect.asSome,
284 Effect.catchTags({
285 WorkspacePathOutsideRootError: () =>
286 Effect.succeed(
287 Option.none<{ readonly absolutePath: string; readonly relativePath: string }>(),
288 ),
289 }),
290 );
291 if (Option.isNone(candidate)) {
292 continue;
293 }
294 const stats = yield* optionOnMissing(fileSystem.stat(candidate.value.absolutePath)).pipe(
295 Effect.mapError(
296 (cause) =>
297 new ProjectFaviconResolutionError({
298 operation: "stat-candidate",
299 workspaceRoot: projectCwd,
300 relativePath,
301 absolutePath: candidate.value.absolutePath,
302 cause,
303 }),
304 ),
305 );
306 if (Option.isSome(stats) && stats.value.type === "File") {
307 return candidate.value.absolutePath;
308 }
309 }
310 return null;
311 });
312
313 const findIconFromSource = Effect.fn("ProjectFaviconResolver.findIconFromSource")(function* (
314 projectCwd: string,
315 sourceFile: string,
316 ): Effect.fn.Return<string | null, ProjectFaviconResolutionError> {
317 const sourcePath = yield* workspacePaths
318 .resolveRelativePathWithinRoot({
319 workspaceRoot: projectCwd,
320 relativePath: sourceFile,
321 })
322 .pipe(
323 Effect.mapError(
324 (cause) =>
325 new ProjectFaviconResolutionError({
326 operation: "resolve-path",
327 workspaceRoot: projectCwd,
328 relativePath: sourceFile,
329 cause,
330 }),
331 ),
332 );
333 const stats = yield* optionOnMissing(fileSystem.stat(sourcePath.absolutePath)).pipe(
334 Effect.mapError(
335 (cause) =>
336 new ProjectFaviconResolutionError({
337 operation: "stat-candidate",
338 workspaceRoot: projectCwd,
339 relativePath: sourceFile,
340 absolutePath: sourcePath.absolutePath,
341 cause,
342 }),
343 ),
344 );
345 if (Option.isNone(stats) || stats.value.type !== "File") {
346 return null;
347 }
348 const source = yield* optionOnMissing(
349 fileSystem.open(sourcePath.absolutePath, { flag: "r" }).pipe(
350 Effect.flatMap((file) => file.readAlloc(ICON_SOURCE_SCAN_BYTES)),
351 Effect.scoped,
352 ),
353 ).pipe(
354 Effect.mapError(
355 (cause) =>
356 new ProjectFaviconResolutionError({
357 operation: "read-source",
358 workspaceRoot: projectCwd,
359 relativePath: sourceFile,
360 absolutePath: sourcePath.absolutePath,
361 cause,
362 }),
363 ),
364 );
365 if (Option.isNone(source) || Option.isNone(source.value)) {
366 return null;
367 }
368 const hrefs = Array.from(
369 extractIconHrefs(new TextDecoder().decode(source.value.value), sourceFile.endsWith(".html")),
370 );
371 const candidates = hrefs.flatMap((href) => resolveIconHref(href, sourceFile));
372 return yield* findExistingFile(projectCwd, candidates, "workspace");
373 });
374
375 // Probe concurrently but join in list order so lower-ranked probes cannot delay a hit.
376 // A failure surfaces only if no earlier probe found a file; scope exit interrupts remaining probes.
377 const firstInOrder = Effect.fn("ProjectFaviconResolver.firstInOrder")(function* <A>(
378 items: ReadonlyArray<A>,
379 probe: (item: A) => Effect.Effect<string | null, ProjectFaviconResolutionError>,
380 ) {
381 const fibers = yield* Effect.forEach(items, (item) => Effect.forkScoped(probe(item)));
382 for (const fiber of fibers) {
383 const found = yield* Fiber.join(fiber);
384 if (found) {
385 return found;
386 }
387 }
388 return null;
389 }, Effect.scoped);
390
391 const resolvePathUncached = Effect.fn("ProjectFaviconResolver.resolvePathUncached")(function* (
392 cwd: string,
393 faviconPath?: string,
394 ): Effect.fn.Return<string | null, ProjectFaviconResolutionError> {
395 const projectCwd = yield* workspacePaths.normalizeWorkspaceRoot(cwd).pipe(
396 Effect.mapError(
397 (cause) =>
398 new ProjectFaviconResolutionError({
399 operation: "normalize-workspace",
400 workspaceRoot: cwd,
401 cause,
402 }),
403 ),
404 );
405 if (faviconPath !== undefined) {
406 const existing = yield* findExistingFile(projectCwd, [faviconPath], "filesystem");
407 if (existing) {
408 return existing;
409 }
410 }
411
412 const projectFile = yield* projectFileLoader.load(projectCwd);
413 if (Option.isSome(projectFile) && projectFile.value.iconPath !== undefined) {
414 const existing = yield* findExistingFile(
415 projectCwd,
416 [projectFile.value.iconPath],
417 "workspace",
418 );
419 if (existing) {
420 return existing;
421 }
422 }
423
424 const wellKnown = yield* firstInOrder(FAVICON_CANDIDATES, (candidate) =>
425 findExistingFile(projectCwd, [candidate], "workspace"),
426 );
427 if (wellKnown) {
428 return wellKnown;
429 }
430
431 const sourceDeclared = yield* firstInOrder(ICON_SOURCE_FILES, (sourceFile) =>
432 findIconFromSource(projectCwd, sourceFile),
433 );
434 if (sourceDeclared) {
435 return sourceDeclared;
436 }
437
438 return yield* findExistingFile(projectCwd, FALLBACK_FAVICON_CANDIDATES, "workspace");
439 });
440
441 const faviconCache = yield* Cache.makeWith<string, string | null, ProjectFaviconResolutionError>(
442 (key) => {
443 const { cwd, faviconPath } = parseFaviconCacheKey(key);
444 return resolvePathUncached(cwd, faviconPath);
445 },
446 {
447 capacity: FAVICON_CACHE_CAPACITY,
448 timeToLive: Exit.match({
449 onSuccess: (value: string | null) =>
450 value === null ? FAVICON_NEGATIVE_CACHE_TTL : FAVICON_POSITIVE_CACHE_TTL,
451 onFailure: (cause) =>
452 Option.exists(Cause.findErrorOption(cause), isMissingWorkspaceRoot)
453 ? FAVICON_NEGATIVE_CACHE_TTL
454 : Duration.zero,
455 }),
456 },
457 );
458
459 const resolvePath: ProjectFaviconResolver["Service"]["resolvePath"] = Effect.fn(
460 "ProjectFaviconResolver.resolvePath",
461 )(function* (cwd, faviconPath) {
462 const key = faviconCacheKey(cwd, faviconPath);
463 const cached = yield* Cache.get(faviconCache, key);
464 if (cached === null) {
465 return null;
466 }
467
468 const stats = yield* optionOnMissing(fileSystem.stat(cached)).pipe(
469 Effect.mapError(
470 (cause) =>
471 new ProjectFaviconResolutionError({
472 operation: "stat-candidate",
473 workspaceRoot: cwd,
474 absolutePath: cached,
475 cause,
476 }),
477 ),
478 );
479 if (Option.isSome(stats) && stats.value.type === "File") {
480 return cached;
481 }
482
483 yield* Cache.invalidate(faviconCache, key);
484 return yield* Cache.get(faviconCache, key);
485 });
486
487 const invalidate: ProjectFaviconResolver["Service"]["invalidate"] = (cwd) =>
488 Cache.keys(faviconCache).pipe(
489 Effect.flatMap((keys) =>
490 Effect.forEach(
491 Array.from(keys).filter((key) => parseFaviconCacheKey(key).cwd === cwd),
492 (key) => Cache.invalidate(faviconCache, key),
493 { discard: true },
494 ),
495 ),
496 );
497
498 return ProjectFaviconResolver.of({ resolvePath, invalidate });
499});
500
501export const layer = Layer.effect(ProjectFaviconResolver, make);