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

ProjectFaviconResolver.ts

266 lines8.5 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 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 }
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;
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 ): Effect.fn.Return<string | null, ProjectFaviconResolutionError> {
141 for (const relativePath of relativeCandidates) {
142 const candidate = yield* workspacePaths
143 .resolveRelativePathWithinRoot({
144 workspaceRoot: projectCwd,
145 relativePath,
146 })
147 .pipe(
148 Effect.map(Option.some),
149 Effect.catchTags({
150 WorkspacePathOutsideRootError: () =>
151 Effect.succeed(
152 Option.none<{ readonly absolutePath: string; readonly relativePath: string }>(),
153 ),
154 }),
155 );
156 if (Option.isNone(candidate)) {
157 continue;
158 }
159 const stats = yield* optionOnNotFound(fileSystem.stat(candidate.value.absolutePath)).pipe(
160 Effect.mapError(
161 (cause) =>
162 new ProjectFaviconResolutionError({
163 operation: "stat-candidate",
164 workspaceRoot: projectCwd,
165 relativePath,
166 absolutePath: candidate.value.absolutePath,
167 cause,
168 }),
169 ),
170 );
171 if (Option.isSome(stats) && stats.value.type === "File") {
172 return candidate.value.absolutePath;
173 }
174 }
175 return null;
176 });
177​
178 const resolvePath: ProjectFaviconResolver["Service"]["resolvePath"] = Effect.fn(
179 "ProjectFaviconResolver.resolvePath",
180 )(function* (cwd, faviconPath) {
181 const projectCwd = yield* workspacePaths.normalizeWorkspaceRoot(cwd).pipe(
182 Effect.mapError(
183 (cause) =>
184 new ProjectFaviconResolutionError({
185 operation: "normalize-workspace",
186 workspaceRoot: cwd,
187 cause,
188 }),
189 ),
190 );
191 // A grouped project's saved path can be absent from one checkout. Use it
192 // where it exists and retain automatic discovery for the other checkouts.
193 if (faviconPath !== undefined) {
194 const existing = yield* findExistingFile(projectCwd, [faviconPath]);
195 if (existing) {
196 return existing;
197 }
198 }
199​
200 // A t3.json iconPath takes precedence over the well-known locations.
201 const projectFile = yield* projectFileLoader.load(projectCwd);
202 if (Option.isSome(projectFile) && projectFile.value.iconPath !== undefined) {
203 const existing = yield* findExistingFile(projectCwd, [projectFile.value.iconPath]);
204 if (existing) {
205 return existing;
206 }
207 }
208​
209 for (const candidate of FAVICON_CANDIDATES) {
210 const existing = yield* findExistingFile(projectCwd, [candidate]);
211 if (existing) {
212 return existing;
213 }
214 }
215​
216 for (const sourceFile of ICON_SOURCE_FILES) {
217 const sourcePath = yield* workspacePaths
218 .resolveRelativePathWithinRoot({
219 workspaceRoot: projectCwd,
220 relativePath: sourceFile,
221 })
222 .pipe(
223 Effect.mapError(
224 (cause) =>
225 new ProjectFaviconResolutionError({
226 operation: "resolve-path",
227 workspaceRoot: projectCwd,
228 relativePath: sourceFile,
229 cause,
230 }),
231 ),
232 );
233 const source = yield* optionOnNotFound(
234 fileSystem.readFileString(sourcePath.absolutePath),
235 ).pipe(
236 Effect.mapError(
237 (cause) =>
238 new ProjectFaviconResolutionError({
239 operation: "read-source",
240 workspaceRoot: projectCwd,
241 relativePath: sourceFile,
242 absolutePath: sourcePath.absolutePath,
243 cause,
244 }),
245 ),
246 );
247 if (Option.isNone(source)) {
248 continue;
249 }
250 const href = extractIconHref(source.value);
251 if (!href) {
252 continue;
253 }
254 const existing = yield* findExistingFile(projectCwd, resolveIconHref(href));
255 if (existing) {
256 return existing;
257 }
258 }
259​
260 return null;
261 });
262​
263 return ProjectFaviconResolver.of({ resolvePath });
264});
265​
266export const layer = Layer.effect(ProjectFaviconResolver, make);