mirror of
https://github.com/HKUDS/DeepTutor.git
synced 2026-12-02 05:29:49 +08:00
Ship folder-based workspaces and data migration, daily practice, redesigned provider and model settings, and streaming conversation improvements. Synchronize README translations and document the archive/permanent-delete upgrade behavior in assets/releases/ver1-6-9.md. Reduce initial JavaScript by deduplicating English resources and loading animation features after hydration. Keep the existing route size budgets. Update regression fixtures and browser audits for scoped URLs and the new settings and learning interfaces.
70 lines
1.5 KiB
TypeScript
70 lines
1.5 KiB
TypeScript
import { activeWorkspaceId } from "./workspace-scope";
|
|
|
|
type CacheEntry<T> = {
|
|
data?: T;
|
|
promise?: Promise<T>;
|
|
expiresAt: number;
|
|
};
|
|
|
|
const clientCache = new Map<string, CacheEntry<unknown>>();
|
|
|
|
interface CacheOptions {
|
|
ttlMs?: number;
|
|
force?: boolean;
|
|
}
|
|
|
|
export async function withClientCache<T>(
|
|
key: string,
|
|
loader: () => Promise<T>,
|
|
options: CacheOptions = {},
|
|
): Promise<T> {
|
|
const { ttlMs = 30_000, force = false } = options;
|
|
|
|
if (typeof window === "undefined") {
|
|
return loader();
|
|
}
|
|
|
|
const now = Date.now();
|
|
key = `${key}:workspace=${activeWorkspaceId()}`;
|
|
const cached = clientCache.get(key) as CacheEntry<T> | undefined;
|
|
if (!force && cached) {
|
|
if (cached.data !== undefined && cached.expiresAt > now) {
|
|
return cached.data;
|
|
}
|
|
if (cached.promise) {
|
|
return cached.promise;
|
|
}
|
|
}
|
|
|
|
const promise = loader()
|
|
.then((value) => {
|
|
// Invalidated or superseded requests must not repopulate stale data.
|
|
if (clientCache.get(key)?.promise === promise) {
|
|
clientCache.set(key, {
|
|
data: value,
|
|
expiresAt: Date.now() + ttlMs,
|
|
});
|
|
}
|
|
return value;
|
|
})
|
|
.catch((error) => {
|
|
if (clientCache.get(key)?.promise === promise) clientCache.delete(key);
|
|
throw error;
|
|
});
|
|
|
|
clientCache.set(key, {
|
|
promise,
|
|
expiresAt: now + ttlMs,
|
|
});
|
|
|
|
return promise;
|
|
}
|
|
|
|
export function invalidateClientCache(prefix: string): void {
|
|
for (const key of clientCache.keys()) {
|
|
if (key.startsWith(prefix)) {
|
|
clientCache.delete(key);
|
|
}
|
|
}
|
|
}
|