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

browserFaviconStore.ts

355 lines12.3 KB

1import {
2 parseScopedProjectKey,
3 scopedProjectKey,
4 scopedThreadKey,
5 scopeProjectRef,
6} from "@t3tools/client-runtime/environment";
7import type { DesktopPreviewFavicon, ScopedProjectRef, ScopedThreadRef } from "@t3tools/contracts";
8import * as Option from "effect/Option";
9import { create } from "zustand";
10import { createJSONStorage, persist } from "zustand/middleware";
11​
12import { normalizeHostname } from "~/browser/browserTargetResolver";
13import { readThreadShell, useQuietThreadShell } from "~/state/entities";
14import { readPreparedConnection, usePreparedConnection } from "~/state/session";
15​
16import {
17 BROWSER_FAVICON_MAX_ALIASES_PER_ENTRY,
18 type BrowserFaviconEntry,
19 canCanonicalizeFaviconWithoutEnvironment,
20 evictExcessFavicons,
21 faviconKey,
22 faviconStorageLocation,
23 isStorableFaviconDataUrl,
24 isValidFaviconCapturedAt,
25 migratePersistedBrowserFaviconState,
26} from "./browserFaviconLogic";
27import { useComposerDraftStore } from "./composerDraftStore";
28import { createMemoryStorage, type StateStorage } from "./lib/storage";
29​
30const BROWSER_FAVICON_STORAGE_KEY = "t3code:browser-favicons:v1";
31const MAX_PENDING_ORIGINS_PER_THREAD = 10;
32const MAX_PENDING_THREADS = 20;
33​
34type PendingFavicon = DesktopPreviewFavicon;
35type PendingFaviconsByOrigin = Record<string, PendingFavicon>;
36​
37export interface BrowserFaviconStoreState {
38 byKey: Record<string, BrowserFaviconEntry>;
39 pendingByThreadKey: Record<string, PendingFaviconsByOrigin>;
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 recordFavicon: (key, dataUrl, capturedAt, aliases = []) =>
125 set((state) => {
126 if (!isStorableFaviconDataUrl(dataUrl)) return state;
127 if (!isValidFaviconCapturedAt(capturedAt)) return state;
128 const existing = state.byKey[key];
129 const aliasCandidates =
130 capturedAt > (existing?.capturedAt ?? -1)
131 ? [...aliases, ...(existing?.aliases ?? [])]
132 : [...(existing?.aliases ?? []), ...aliases];
133 const nextAliases = [...new Set(aliasCandidates)].slice(
134 0,
135 BROWSER_FAVICON_MAX_ALIASES_PER_ENTRY,
136 );
137 const aliasesUnchanged =
138 nextAliases.length === (existing?.aliases?.length ?? 0) &&
139 nextAliases.every((alias, index) => alias === existing?.aliases?.[index]);
140 if (existing && capturedAt <= existing.capturedAt && aliasesUnchanged) return state;
141 return {
142 byKey: evictExcessFavicons({
143 ...state.byKey,
144 [key]: {
145 dataUrl: capturedAt > (existing?.capturedAt ?? -1) ? dataUrl : existing!.dataUrl,
146 capturedAt: Math.max(capturedAt, existing?.capturedAt ?? -1),
147 ...(nextAliases.length > 0 ? { aliases: nextAliases } : {}),
148 },
149 }),
150 };
151 }),
152 }),
153 {
154 name: BROWSER_FAVICON_STORAGE_KEY,
155 version: 1,
156 storage: createJSONStorage(resolveBrowserFaviconStorage),
157 partialize: (state) => ({ byKey: state.byKey }),
158 migrate: migratePersistedBrowserFaviconState,
159 merge: mergeBrowserFaviconState,
160 },
161 ),
162);
163​
164function mergeBrowserFaviconState(
165 persistedState: unknown,
166 currentState: BrowserFaviconStoreState,
167): BrowserFaviconStoreState {
168 return {
169 ...currentState,
170 ...migratePersistedBrowserFaviconState(persistedState),
171 };
173​
174/** Server threads name their project in the shell; drafts in the composer draft store. */
175function useFaviconProjectRefForThread(threadRef: ScopedThreadRef): ScopedProjectRef | null {
176 const shell = useQuietThreadShell(threadRef);
177 const draftProjectRef = useComposerDraftStore((state) => {
178 const draft = state.draftThreadsByThreadKey[scopedThreadKey(threadRef)];
179 return draft ? scopedProjectKey(scopeProjectRef(draft.environmentId, draft.projectId)) : null;
180 });
181 if (shell?.projectId) return scopeProjectRef(threadRef.environmentId, shell.projectId);
182 return draftProjectRef === null ? null : parseScopedProjectKey(draftProjectRef);
184​
185function readThreadProjectRef(threadRef: ScopedThreadRef): ScopedProjectRef | null {
186 const projectId = readThreadShell(threadRef)?.projectId;
187 if (projectId) return scopeProjectRef(threadRef.environmentId, projectId);
188 const draft =
189 useComposerDraftStore.getState().draftThreadsByThreadKey[scopedThreadKey(threadRef)];
190 return draft ? scopeProjectRef(draft.environmentId, draft.projectId) : null;
192​
193export function recordFaviconForProject(
194 projectRef: ScopedProjectRef,
195 favicon: DesktopPreviewFavicon,
196 environmentHostname: string | null,
197): boolean {
198 if (!isStorableFaviconDataUrl(favicon.dataUrl) || !isValidFaviconCapturedAt(favicon.capturedAt)) {
199 return false;
200 }
201 const location = faviconStorageLocation(
202 scopedProjectKey(projectRef),
203 favicon.pageUrl,
204 environmentHostname,
205 );
206 if (!location) return false;
207 const state = useBrowserFaviconStore.getState();
208 const existing = state.byKey[location.key];
209 if (
210 existing &&
211 existing.capturedAt >= favicon.capturedAt &&
212 location.aliases.every((alias) => existing.aliases?.includes(alias))
213 )
214 return true;
215 state.recordFavicon(location.key, favicon.dataUrl, favicon.capturedAt, location.aliases);
216 return true;
218​
219/**
220 * The thread's project and environment host may not be known yet when a capture
221 * arrives; such captures wait per thread and land with the next capture that can
222 * resolve them.
223 */
224export function recordFaviconForThread(
225 threadRef: ScopedThreadRef,
226 favicon: DesktopPreviewFavicon,
227): boolean {
228 if (
229 !isStorableFaviconDataUrl(favicon.dataUrl) ||
230 !isValidFaviconCapturedAt(favicon.capturedAt) ||
231 !pendingOriginKey(favicon.pageUrl)
232 )
233 return false;
234 const projectRef = readThreadProjectRef(threadRef);
235 const connection = readPreparedConnection(threadRef.environmentId);
236 const environmentHostname = connection ? new URL(connection.httpBaseUrl).hostname : undefined;
237 if (projectRef) flushPendingFaviconsForThread(threadRef, projectRef, environmentHostname);
238 const hostname =
239 environmentHostname !== undefined
240 ? environmentHostname
241 : canCanonicalizeFaviconWithoutEnvironment(favicon.pageUrl)
242 ? null
243 : undefined;
244 if (
245 projectRef &&
246 hostname !== undefined &&
247 recordFaviconForProject(projectRef, favicon, hostname)
248 ) {
249 return true;
250 }
251 const threadKey = scopedThreadKey(threadRef);
252 const state = useBrowserFaviconStore.getState();
253 const pendingByThreadKey = addPendingFavicon(state.pendingByThreadKey, threadKey, favicon);
254 if (pendingByThreadKey !== state.pendingByThreadKey) {
255 useBrowserFaviconStore.setState({ pendingByThreadKey });
256 }
257 return false;
259​
260function flushPendingFaviconsForThread(
261 threadRef: ScopedThreadRef,
262 projectRef: ScopedProjectRef,
263 environmentHostname: string | undefined,
264): boolean {
265 const threadKey = scopedThreadKey(threadRef);
266 const pending = useBrowserFaviconStore.getState().pendingByThreadKey[threadKey];
267 if (!pending) return true;
268 const remaining = Object.fromEntries(
269 Object.entries(pending).filter(([, favicon]) => {
270 const hostname =
271 environmentHostname !== undefined
272 ? environmentHostname
273 : canCanonicalizeFaviconWithoutEnvironment(favicon.pageUrl)
274 ? null
275 : undefined;
276 return hostname === undefined || !recordFaviconForProject(projectRef, favicon, hostname);
277 }),
278 );
279 useBrowserFaviconStore.setState((state) => {
280 const pendingByThreadKey = { ...state.pendingByThreadKey };
281 if (Object.keys(remaining).length === 0) delete pendingByThreadKey[threadKey];
282 else pendingByThreadKey[threadKey] = remaining;
283 return { pendingByThreadKey };
284 });
285 return Object.keys(remaining).length === 0;
287​
288export function useFaviconForThreadUrl(threadRef: ScopedThreadRef, url: string): string | null {
289 const projectRef = useFaviconProjectRefForThread(threadRef);
290 const preparedConnection = usePreparedConnection(threadRef.environmentId);
291 const environmentHostname = Option.isSome(preparedConnection)
292 ? new URL(preparedConnection.value.httpBaseUrl).hostname
293 : null;
294 const threadKey = scopedThreadKey(threadRef);
295 return useBrowserFaviconStore((state) =>
296 lookupFaviconForThread(state, threadKey, projectRef, url, environmentHostname),
297 );
299​
300/**
301 * A capture waiting for its thread's project still shows on that thread, and wins
302 * over an older stored capture for the same origin.
303 */
304export function lookupFaviconForThread(
305 state: Pick<BrowserFaviconStoreState, "byKey" | "pendingByThreadKey">,
306 threadKey: string,
307 projectRef: ScopedProjectRef | null,
308 url: string,
309 environmentHostname: string | null,
310): string | null {
311 const stored = lookupFaviconEntry(state.byKey, projectRef, url, environmentHostname);
312 const originKey = pendingOriginKey(url);
313 const pending = originKey ? state.pendingByThreadKey[threadKey]?.[originKey] : undefined;
314 if (pending && (!stored || pending.capturedAt > stored.capturedAt)) return pending.dataUrl;
315 return stored?.dataUrl ?? null;
317​
318export function lookupFavicon(
319 byKey: Record<string, BrowserFaviconEntry>,
320 projectRef: ScopedProjectRef | null,
321 url: string,
322 environmentHostname: string | null,
323): string | null {
324 return lookupFaviconEntry(byKey, projectRef, url, environmentHostname)?.dataUrl ?? null;
326​
327function lookupFaviconEntry(
328 byKey: Record<string, BrowserFaviconEntry>,
329 projectRef: ScopedProjectRef | null,
330 url: string,
331 environmentHostname: string | null,
332): BrowserFaviconEntry | null {
333 const key = projectRef
334 ? faviconKey(scopedProjectKey(projectRef), url, environmentHostname)
335 : null;
336 if (!key) return null;
337 const direct = byKey[key];
338 if (direct) return direct;
339 try {
340 const requestedHost = normalizeHostname(new URL(url).hostname);
341 const localKey = faviconKey(scopedProjectKey(projectRef!), url, requestedHost);
342 const localEntry = localKey ? byKey[localKey] : null;
343 return localEntry?.aliases?.includes(requestedHost) ? localEntry : null;
344 } catch {
345 return null;
346 }
348​
349export function resetBrowserFaviconsForTests(): void {
350 useBrowserFaviconStore.setState({
351 byKey: {},
352 pendingByThreadKey: {},
353 });
354 useBrowserFaviconStore.persist.clearStorage();