Remove 19 unused source files (no importers anywhere in src/):
- src/actions/admin-permissions.ts, admin-radio.ts, admin-user-edit.ts,
admin-users.ts (functionality lives in @/actions/users and
@/actions/permissions)
- src/components/admin/confirm-action.tsx, page-header.tsx
- src/components/motion-elements.tsx
- src/lib/format-date.ts
- src/lib/catalog-categories/* (incl. re-export barrel)
- src/lib/foundation/{index,database,middleware,validation}.ts (errors/action
kept, still imported directly)
- src/lib/services/imager/{avatar-renderer,memory-cache}.ts
- src/lib/services/nitro-assets.ts
Update admin-operations-contract test to drop the two removed action-file
gates (their permission coverage already exists in users.ts/permissions.ts).
Add knip.json for repeatable dead-code audits.
Verified: tsc --noEmit clean, next build succeeds, full test suite green
(301/301).
This commit is contained in:
1 parent
60eb45be73
commit
3c9c1311ec
23 files changed
+586
-2158
No files matched your search
@@ -1,190 +0,0 @@
|
||||
/**
|
||||
* Self-hosted avatar imager — Phase 1.
|
||||
*
|
||||
* Pipeline (cascade):
|
||||
* 1. In-memory LRU cache → instant
|
||||
* 2. Disk cache → fast
|
||||
* 3. In-flight dedup → coalesce thundering herd
|
||||
* 4. Upstream Habbo proxy → save to disk + memory
|
||||
* 5. Transparent fallback → never break the UI
|
||||
*/
|
||||
|
||||
import { createHash } from "node:crypto";
|
||||
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import { dirname, join } from "node:path";
|
||||
import { siteSettings } from "@/lib/services/site-settings";
|
||||
import { InFlight, LruCache, NegativeCache } from "./memory-cache";
|
||||
|
||||
const CACHE_DIR = join(process.cwd(), "public", "cache", "avatars");
|
||||
const DEFAULT_UPSTREAM = "https://www.habbo.com/habbo-imaging/avatarimage";
|
||||
|
||||
const MEM_CACHE_CAPACITY = 500;
|
||||
const NEGATIVE_CACHE_TTL_MS = 60_000;
|
||||
const UPSTREAM_TIMEOUT_MS = 10_000;
|
||||
|
||||
// 1×1 transparent PNG (67 bytes) — served when both local and upstream fail.
|
||||
const TRANSPARENT_PNG = Buffer.from(
|
||||
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkAAIAAAoAAv/lxKUAAAAASUVORK5CYII=",
|
||||
"base64",
|
||||
);
|
||||
|
||||
export interface AvatarRenderOptions {
|
||||
figure: string;
|
||||
size?: "s" | "m" | "l";
|
||||
direction?: number;
|
||||
headDirection?: number;
|
||||
headOnly?: boolean;
|
||||
gesture?: string;
|
||||
action?: string;
|
||||
}
|
||||
|
||||
export interface AvatarRenderResult {
|
||||
buffer: Buffer;
|
||||
etag: string;
|
||||
source: "memory" | "disk" | "upstream" | "fallback";
|
||||
}
|
||||
|
||||
const memCache = new LruCache<Buffer>(MEM_CACHE_CAPACITY);
|
||||
const inFlight = new InFlight<AvatarRenderResult>();
|
||||
const negativeCache = new NegativeCache(NEGATIVE_CACHE_TTL_MS);
|
||||
|
||||
function getCacheKey(opts: AvatarRenderOptions): string {
|
||||
const raw = [
|
||||
opts.figure,
|
||||
opts.size ?? "m",
|
||||
opts.direction ?? 2,
|
||||
opts.headDirection ?? 3,
|
||||
opts.headOnly ? "h" : "f",
|
||||
opts.gesture ?? "",
|
||||
opts.action ?? "",
|
||||
].join("_");
|
||||
return createHash("md5").update(raw).digest("hex");
|
||||
}
|
||||
|
||||
function getCachePath(key: string): string {
|
||||
return join(CACHE_DIR, key.slice(0, 2), `${key}.png`);
|
||||
}
|
||||
|
||||
function makeEtag(key: string): string {
|
||||
return `W/"${key}"`;
|
||||
}
|
||||
|
||||
function saveToCache(cachePath: string, data: Buffer): void {
|
||||
try {
|
||||
const dir = dirname(cachePath);
|
||||
if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
|
||||
writeFileSync(cachePath, data);
|
||||
} catch {
|
||||
/* non-fatal */
|
||||
}
|
||||
}
|
||||
|
||||
function isPng(buf: Buffer): boolean {
|
||||
return (
|
||||
buf.length > 8 &&
|
||||
buf[0] === 0x89 &&
|
||||
buf[1] === 0x50 &&
|
||||
buf[2] === 0x4e &&
|
||||
buf[3] === 0x47
|
||||
);
|
||||
}
|
||||
|
||||
async function resolveUpstreamBase(): Promise<string> {
|
||||
const fromEnv = process.env.IMAGING_UPSTREAM_URL?.trim();
|
||||
if (fromEnv) return fromEnv.replace(/\/+$/, "");
|
||||
const fromSettings =
|
||||
(await siteSettings.get("habbo_imaging_url", DEFAULT_UPSTREAM)) ??
|
||||
DEFAULT_UPSTREAM;
|
||||
return fromSettings.replace(/\/+$/, "") || DEFAULT_UPSTREAM;
|
||||
}
|
||||
|
||||
async function fetchUpstream(opts: AvatarRenderOptions): Promise<Buffer | null> {
|
||||
try {
|
||||
const params = new URLSearchParams({
|
||||
figure: opts.figure,
|
||||
direction: String(opts.direction ?? 2),
|
||||
head_direction: String(opts.headDirection ?? 3),
|
||||
size: opts.size ?? "m",
|
||||
});
|
||||
if (opts.headOnly) params.set("headonly", "1");
|
||||
if (opts.gesture) params.set("gesture", opts.gesture);
|
||||
if (opts.action) params.set("action", opts.action);
|
||||
|
||||
const base = await resolveUpstreamBase();
|
||||
const url = `${base}?${params.toString()}`;
|
||||
const res = await fetch(url, {
|
||||
signal: AbortSignal.timeout(UPSTREAM_TIMEOUT_MS),
|
||||
headers: { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)" },
|
||||
});
|
||||
if (!res.ok) return null;
|
||||
|
||||
const buffer = Buffer.from(await res.arrayBuffer());
|
||||
return isPng(buffer) ? buffer : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get an avatar image. Always returns a result — never throws, never returns
|
||||
* null. Worst case is a 1×1 transparent PNG so the UI never shows broken
|
||||
* images.
|
||||
*/
|
||||
export async function renderAvatar(
|
||||
opts: AvatarRenderOptions,
|
||||
): Promise<AvatarRenderResult> {
|
||||
const key = getCacheKey(opts);
|
||||
const etag = makeEtag(key);
|
||||
|
||||
const fromMem = memCache.get(key);
|
||||
if (fromMem) return { buffer: fromMem, etag, source: "memory" };
|
||||
|
||||
const cachePath = getCachePath(key);
|
||||
if (existsSync(cachePath)) {
|
||||
try {
|
||||
const buf = readFileSync(cachePath);
|
||||
memCache.set(key, buf);
|
||||
return { buffer: buf, etag, source: "disk" };
|
||||
} catch {
|
||||
/* fall through to fetch */
|
||||
}
|
||||
}
|
||||
|
||||
if (negativeCache.isMarked(key)) {
|
||||
return { buffer: TRANSPARENT_PNG, etag, source: "fallback" };
|
||||
}
|
||||
|
||||
return inFlight.dedup(key, async () => {
|
||||
if (existsSync(cachePath)) {
|
||||
try {
|
||||
const buf = readFileSync(cachePath);
|
||||
memCache.set(key, buf);
|
||||
return { buffer: buf, etag, source: "disk" };
|
||||
} catch {
|
||||
/* fall through */
|
||||
}
|
||||
}
|
||||
|
||||
const useUpstream =
|
||||
(await siteSettings.get("imaging_use_habbo_fallback", "1")) === "1";
|
||||
if (useUpstream) {
|
||||
const upstream = await fetchUpstream(opts);
|
||||
if (upstream) {
|
||||
saveToCache(cachePath, upstream);
|
||||
memCache.set(key, upstream);
|
||||
return { buffer: upstream, etag, source: "upstream" };
|
||||
}
|
||||
}
|
||||
|
||||
negativeCache.mark(key);
|
||||
return { buffer: TRANSPARENT_PNG, etag, source: "fallback" };
|
||||
});
|
||||
}
|
||||
|
||||
export function getImagerStats() {
|
||||
return {
|
||||
memCacheSize: memCache.size,
|
||||
memCacheCapacity: MEM_CACHE_CAPACITY,
|
||||
cacheDir: CACHE_DIR,
|
||||
};
|
||||
}
|
||||
@@ -1,97 +0,0 @@
|
||||
/**
|
||||
* Tiny LRU + in-flight dedup utilities for the avatar imager.
|
||||
* Pure in-house, zero deps. Map preserves insertion order, so we
|
||||
* implement LRU by deleting + re-inserting on access.
|
||||
*/
|
||||
|
||||
export class LruCache<V> {
|
||||
private map = new Map<string, V>();
|
||||
|
||||
constructor(private readonly capacity: number) {}
|
||||
|
||||
get(key: string): V | undefined {
|
||||
const v = this.map.get(key);
|
||||
if (v === undefined) return undefined;
|
||||
this.map.delete(key);
|
||||
this.map.set(key, v);
|
||||
return v;
|
||||
}
|
||||
|
||||
set(key: string, value: V): void {
|
||||
if (this.map.has(key)) this.map.delete(key);
|
||||
this.map.set(key, value);
|
||||
if (this.map.size > this.capacity) {
|
||||
const oldest = this.map.keys().next().value;
|
||||
if (oldest !== undefined) this.map.delete(oldest);
|
||||
}
|
||||
}
|
||||
|
||||
has(key: string): boolean {
|
||||
return this.map.has(key);
|
||||
}
|
||||
|
||||
delete(key: string): void {
|
||||
this.map.delete(key);
|
||||
}
|
||||
|
||||
clear(): void {
|
||||
this.map.clear();
|
||||
}
|
||||
|
||||
get size(): number {
|
||||
return this.map.size;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* In-flight request deduplication. If N callers ask for the same key
|
||||
* concurrently, only the first one runs `loader` and the rest await
|
||||
* the same Promise.
|
||||
*/
|
||||
export class InFlight<V> {
|
||||
private pending = new Map<string, Promise<V>>();
|
||||
|
||||
async dedup(key: string, loader: () => Promise<V>): Promise<V> {
|
||||
const existing = this.pending.get(key);
|
||||
if (existing) return existing;
|
||||
const p = loader().finally(() => {
|
||||
this.pending.delete(key);
|
||||
});
|
||||
this.pending.set(key, p);
|
||||
return p;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Negative cache: marks a key as "known to fail" for `ttlMs` so we don't
|
||||
* hammer the upstream / re-attempt expensive renders for broken figures.
|
||||
*/
|
||||
export class NegativeCache {
|
||||
private map = new Map<string, number>();
|
||||
|
||||
constructor(private readonly ttlMs: number) {}
|
||||
|
||||
isMarked(key: string): boolean {
|
||||
const exp = this.map.get(key);
|
||||
if (exp === undefined) return false;
|
||||
if (Date.now() > exp) {
|
||||
this.map.delete(key);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
mark(key: string): void {
|
||||
this.map.set(key, Date.now() + this.ttlMs);
|
||||
if (this.map.size > 1000) {
|
||||
const now = Date.now();
|
||||
for (const [k, exp] of this.map) {
|
||||
if (now > exp) this.map.delete(k);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
clear(): void {
|
||||
this.map.clear();
|
||||
}
|
||||
}
|
||||
@@ -1,74 +0,0 @@
|
||||
import { promises as fs } from "node:fs";
|
||||
import path from "node:path";
|
||||
import { matchCategory, normalizeName } from "@/lib/catalog-categories";
|
||||
import { getAncestors } from "@/lib/services/catalog-tree";
|
||||
import { getFurniAssetDirs } from "@/lib/services/furni-asset-dirs";
|
||||
|
||||
/**
|
||||
* Categorize a file using matchCategory logic.
|
||||
* Returns the category key.
|
||||
*/
|
||||
export function categorizeFile(filename: string): string {
|
||||
const name = filename.replace(/\.nitro$/, "");
|
||||
const cat = matchCategory(normalizeName(name));
|
||||
return cat.key;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a nested folder path from catalog page ancestors.
|
||||
* Example: page "HC Rares" under "Rares" under "Furni" → "furni/rares/hc-rares"
|
||||
* Includes the root page in the path.
|
||||
*/
|
||||
export async function buildCatalogPath(pageId: number): Promise<string> {
|
||||
const ancestors = await getAncestors(pageId);
|
||||
if (ancestors.length === 0) return "uncategorized";
|
||||
|
||||
return ancestors.map((a) => slugifyPath(a.caption)).join("/");
|
||||
}
|
||||
|
||||
/** Sanitize a catalog page name into a valid folder segment */
|
||||
export function slugifyPath(name: string): string {
|
||||
return (
|
||||
name
|
||||
.toLowerCase()
|
||||
.normalize("NFD")
|
||||
.replace(/[\u0300-\u036f]/g, "")
|
||||
.replace(/[^a-z0-9]+/g, "-")
|
||||
.replace(/^-+|-+$/g, "") || "uncategorized"
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Scan the flat furniture folder for .nitro files.
|
||||
*/
|
||||
export async function scanFlatFolder(): Promise<string[]> {
|
||||
try {
|
||||
const { nitroDir } = await getFurniAssetDirs();
|
||||
const entries = await fs.readdir(nitroDir);
|
||||
return entries.filter((e) => e.endsWith(".nitro"));
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Scan ALL .nitro files recursively (flat + subfolders).
|
||||
* Returns a Set of classnames (filename without .nitro extension).
|
||||
*/
|
||||
export async function scanAllNitroFiles(): Promise<Set<string>> {
|
||||
try {
|
||||
const { nitroDir } = await getFurniAssetDirs();
|
||||
const entries = await fs.readdir(nitroDir, { recursive: true });
|
||||
const classnames = new Set<string>();
|
||||
for (const entry of entries) {
|
||||
const name = typeof entry === "string" ? entry : String(entry);
|
||||
if (name.endsWith(".nitro")) {
|
||||
const basename = path.basename(name, ".nitro");
|
||||
classnames.add(basename);
|
||||
}
|
||||
}
|
||||
return classnames;
|
||||
} catch {
|
||||
return new Set();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user