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

browserFaviconStore.ts

337 lines11.0 KB

1import {
2 scopedProjectKey,
3 scopedThreadKey,
4 scopeProjectRef,
5} from "@t3tools/client-runtime/environment";
6import type { DesktopPreviewFavicon, ScopedProjectRef, ScopedThreadRef } from "@t3tools/contracts";
7import * as Option from "effect/Option";
8import { create } from "zustand";
9import { createJSONStorage, persist } from "zustand/middleware";
10​
11import { normalizeHostname } from "~/browser/browserTargetResolver";
12import { useQuietThreadShell } from "~/state/entities";
13import { usePreparedConnection } from "~/state/session";
14​
15import {
16 BROWSER_FAVICON_MAX_ALIASES_PER_ENTRY,
17 type BrowserFaviconEntry,
18 canCanonicalizeFaviconWithoutEnvironment,
19 evictExcessFavicons,
20 faviconKey,
21 faviconStorageLocation,
22 isStorableFaviconDataUrl,
23 isValidFaviconCapturedAt,
24 migratePersistedBrowserFaviconState,
25} from "./browserFaviconLogic";
26import { createMemoryStorage, type StateStorage } from "./lib/storage";
27​
28const BROWSER_FAVICON_STORAGE_KEY = "t3code:browser-favicons:v1";
29const MAX_PENDING_ORIGINS_PER_THREAD = 10;
30const MAX_PENDING_THREADS = 20;
31const MAX_REGISTERED_THREADS = 100;
32​
33type PendingFavicon = DesktopPreviewFavicon;
34type PendingFaviconsByOrigin = Record<string, PendingFavicon>;
35​
36export interface BrowserFaviconStoreState {
37 byKey: Record<string, BrowserFaviconEntry>;
38 pendingByThreadKey: Record<string, PendingFaviconsByOrigin>;
39 projectRefByThreadKey: Record<string, ScopedProjectRef>;
40 recordFavicon: (
41 key: string,
42 dataUrl: string,
43 capturedAt: number,
44 aliases?: ReadonlyArray<string>,
45 ) => void;
47​
48function pendingOriginKey(pageUrl: string): string | null {
49 return faviconKey("pending", pageUrl, null)?.slice("pending ".length) ?? null;
51​
52function addPendingFavicon(
53 pendingByThreadKey: Record<string, PendingFaviconsByOrigin>,
54 threadKey: string,
55 favicon: PendingFavicon,
56): Record<string, PendingFaviconsByOrigin> {
57 const originKey = pendingOriginKey(favicon.pageUrl);
58 if (!originKey) return pendingByThreadKey;
59 const current = pendingByThreadKey[threadKey] ?? {};
60 const existing = current[originKey];
61 if (existing && existing.capturedAt >= favicon.capturedAt) return pendingByThreadKey;
62 const nextForThread = {
63 ...current,
64 [originKey]: favicon,
65 };
66 const boundedForThread = Object.fromEntries(
67 Object.entries(nextForThread)
68 .toSorted(([, left], [, right]) => right.capturedAt - left.capturedAt)
69 .slice(0, MAX_PENDING_ORIGINS_PER_THREAD),
70 );
71​
72 const withoutThread = { ...pendingByThreadKey };
73 delete withoutThread[threadKey];
74 return Object.fromEntries(
75 [...Object.entries(withoutThread), [threadKey, boundedForThread]].slice(-MAX_PENDING_THREADS),
76 );
78​
79export function resolveBrowserFaviconStorage(): StateStorage {
80 const fallback = createMemoryStorage();
81 const shadowedNames = new Set<string>();
82 let primary: Storage;
83 try {
84 if (typeof window === "undefined") return fallback;
85 primary = window.localStorage;
86 } catch {
87 return fallback;
88 }
89 return {
90 getItem: (name) => {
91 if (shadowedNames.has(name)) return fallback.getItem(name);
92 try {
93 return primary.getItem(name);
94 } catch {
95 return fallback.getItem(name);
96 }
97 },
98 setItem: (name, value) => {
99 fallback.setItem(name, value);
100 try {
101 primary.setItem(name, value);
102 shadowedNames.delete(name);
103 } catch {
104 shadowedNames.add(name);
105 }
106 },
107 removeItem: (name) => {
108 fallback.removeItem(name);
109 try {
110 primary.removeItem(name);
111 shadowedNames.delete(name);
112 } catch {
113 shadowedNames.add(name);
114 }
115 },
116 };
118​
119export const useBrowserFaviconStore = create<BrowserFaviconStoreState>()(
120 persist(
121 (set) => ({
122 byKey: {},
123 pendingByThreadKey: {},
124 projectRefByThreadKey: {},
125 recordFavicon: (key, dataUrl, capturedAt, aliases = []) =>
126 set((state) => {
127 if (!isStorableFaviconDataUrl(dataUrl)) return state;
128 if (!isValidFaviconCapturedAt(capturedAt)) return state;
129 const existing = state.byKey[key];
130 const aliasCandidates =
131 capturedAt > (existing?.capturedAt ?? -1)
132 ? [...aliases, ...(existing?.aliases ?? [])]
133 : [...(existing?.aliases ?? []), ...aliases];
134 const nextAliases = [...new Set(aliasCandidates)].slice(
135 0,
136 BROWSER_FAVICON_MAX_ALIASES_PER_ENTRY,
137 );
138 const aliasesUnchanged =
139 nextAliases.length === (existing?.aliases?.length ?? 0) &&
140 nextAliases.every((alias, index) => alias === existing?.aliases?.[index]);
141 if (existing && capturedAt <= existing.capturedAt && aliasesUnchanged) return state;
142 return {
143 byKey: evictExcessFavicons({
144 ...state.byKey,
145 [key]: {
146 dataUrl: capturedAt > (existing?.capturedAt ?? -1) ? dataUrl : existing!.dataUrl,
147 capturedAt: Math.max(capturedAt, existing?.capturedAt ?? -1),
148 ...(nextAliases.length > 0 ? { aliases: nextAliases } : {}),
149 },
150 }),
151 };
152 }),
153 }),
154 {
155 name: BROWSER_FAVICON_STORAGE_KEY,
156 version: 1,
157 storage: createJSONStorage(resolveBrowserFaviconStorage),
158 partialize: (state) => ({ byKey: state.byKey }),
159 migrate: migratePersistedBrowserFaviconState,
160 merge: mergeBrowserFaviconState,
161 },
162 ),
163);
164​
165export function mergeBrowserFaviconState(
166 persistedState: unknown,
167 currentState: BrowserFaviconStoreState,
168): BrowserFaviconStoreState {
169 return {
170 ...currentState,
171 ...migratePersistedBrowserFaviconState(persistedState),
172 };
174​
175export function registerFaviconProjectForThread(
176 threadRef: ScopedThreadRef,
177 projectRef: ScopedProjectRef,
178): void {
179 const threadKey = scopedThreadKey(threadRef);
180 const state = useBrowserFaviconStore.getState();
181 const current = state.projectRefByThreadKey[threadKey];
182 if (
183 current?.environmentId === projectRef.environmentId &&
184 current.projectId === projectRef.projectId
185 ) {
186 return;
187 }
188 useBrowserFaviconStore.setState({
189 projectRefByThreadKey: Object.fromEntries(
190 [
191 ...Object.entries(state.projectRefByThreadKey).filter(([key]) => key !== threadKey),
192 [threadKey, projectRef],
193 ].slice(-MAX_REGISTERED_THREADS),
194 ),
195 });
197​
198export function useFaviconProjectRefForThread(threadRef: ScopedThreadRef): ScopedProjectRef | null {
199 const shell = useQuietThreadShell(threadRef);
200 const shellProjectId = shell?.projectId ?? null;
201 const environmentId = threadRef.environmentId;
202 const shellProjectRef = shellProjectId ? scopeProjectRef(environmentId, shellProjectId) : null;
203 const registered = useBrowserFaviconStore(
204 (state) => state.projectRefByThreadKey[scopedThreadKey(threadRef)] ?? null,
205 );
206 return shellProjectRef ?? registered;
208​
209export function recordFaviconForProject(
210 projectRef: ScopedProjectRef,
211 favicon: DesktopPreviewFavicon,
212 environmentHostname: string | null,
213): boolean {
214 if (!isStorableFaviconDataUrl(favicon.dataUrl) || !isValidFaviconCapturedAt(favicon.capturedAt)) {
215 return false;
216 }
217 const location = faviconStorageLocation(
218 scopedProjectKey(projectRef),
219 favicon.pageUrl,
220 environmentHostname,
221 );
222 if (!location) return false;
223 const state = useBrowserFaviconStore.getState();
224 const existing = state.byKey[location.key];
225 if (
226 existing &&
227 existing.capturedAt >= favicon.capturedAt &&
228 location.aliases.every((alias) => existing.aliases?.includes(alias))
229 )
230 return true;
231 state.recordFavicon(location.key, favicon.dataUrl, favicon.capturedAt, location.aliases);
232 return true;
234​
235export function recordFaviconForThread(
236 threadRef: ScopedThreadRef,
237 favicon: DesktopPreviewFavicon,
238 projectRef: ScopedProjectRef | null,
239 environmentHostname: string | undefined,
240): boolean {
241 if (
242 !isStorableFaviconDataUrl(favicon.dataUrl) ||
243 !isValidFaviconCapturedAt(favicon.capturedAt) ||
244 !pendingOriginKey(favicon.pageUrl)
245 )
246 return false;
247 const hostname =
248 environmentHostname !== undefined
249 ? environmentHostname
250 : canCanonicalizeFaviconWithoutEnvironment(favicon.pageUrl)
251 ? null
252 : undefined;
253 if (
254 projectRef &&
255 hostname !== undefined &&
256 recordFaviconForProject(projectRef, favicon, hostname)
257 ) {
258 return true;
259 }
260 const threadKey = scopedThreadKey(threadRef);
261 const state = useBrowserFaviconStore.getState();
262 const pendingByThreadKey = addPendingFavicon(state.pendingByThreadKey, threadKey, favicon);
263 if (pendingByThreadKey !== state.pendingByThreadKey) {
264 useBrowserFaviconStore.setState({ pendingByThreadKey });
265 }
266 return false;
268​
269export function flushPendingFaviconsForThread(
270 threadRef: ScopedThreadRef,
271 projectRef: ScopedProjectRef,
272 environmentHostname: string | undefined,
273): boolean {
274 const threadKey = scopedThreadKey(threadRef);
275 const pending = useBrowserFaviconStore.getState().pendingByThreadKey[threadKey];
276 if (!pending) return true;
277 const remaining = Object.fromEntries(
278 Object.entries(pending).filter(([, favicon]) => {
279 const hostname =
280 environmentHostname !== undefined
281 ? environmentHostname
282 : canCanonicalizeFaviconWithoutEnvironment(favicon.pageUrl)
283 ? null
284 : undefined;
285 return hostname === undefined || !recordFaviconForProject(projectRef, favicon, hostname);
286 }),
287 );
288 useBrowserFaviconStore.setState((state) => {
289 const pendingByThreadKey = { ...state.pendingByThreadKey };
290 if (Object.keys(remaining).length === 0) delete pendingByThreadKey[threadKey];
291 else pendingByThreadKey[threadKey] = remaining;
292 return { pendingByThreadKey };
293 });
294 return Object.keys(remaining).length === 0;
296​
297export function useFaviconForThreadUrl(threadRef: ScopedThreadRef, url: string): string | null {
298 const projectRef = useFaviconProjectRefForThread(threadRef);
299 const preparedConnection = usePreparedConnection(threadRef.environmentId);
300 const environmentHostname = Option.isSome(preparedConnection)
301 ? new URL(preparedConnection.value.httpBaseUrl).hostname
302 : null;
303 return useBrowserFaviconStore((state) =>
304 lookupFavicon(state.byKey, projectRef, url, environmentHostname),
305 );
307​
308export function lookupFavicon(
309 byKey: Record<string, BrowserFaviconEntry>,
310 projectRef: ScopedProjectRef | null,
311 url: string,
312 environmentHostname: string | null,
313): string | null {
314 const key = projectRef
315 ? faviconKey(scopedProjectKey(projectRef), url, environmentHostname)
316 : null;
317 if (!key) return null;
318 const direct = byKey[key];
319 if (direct) return direct.dataUrl;
320 try {
321 const requestedHost = normalizeHostname(new URL(url).hostname);
322 const localKey = faviconKey(scopedProjectKey(projectRef!), url, requestedHost);
323 const localEntry = localKey ? byKey[localKey] : null;
324 return localEntry?.aliases?.includes(requestedHost) ? localEntry.dataUrl : null;
325 } catch {
326 return null;
327 }
329​
330export function resetBrowserFaviconsForTests(): void {
331 useBrowserFaviconStore.setState({
332 byKey: {},
333 pendingByThreadKey: {},
334 projectRefByThreadKey: {},
335 });
336 useBrowserFaviconStore.persist.clearStorage();