Files
Kaname/src/lib/hub/client.ts
T
Pascal LinxweilerandClaude Opus 5.5 1527fcd830 Hugging Face style model pages at /<org>/<name>
- Model URLs are the repo path (case-insensitive, canonical redirect);
  /models/<id> redirects
- Header with avatar, org/name + copy, task/format/arch/language/license
  pills, user tags, cross-links to the Hub (files @ sha, commits, community,
  base model) and tabs: rendered model card at the pinned commit, files, jobs
- Sidebar: download card, local copy, model tree with related local models
- Metadata gains author avatar and base relation (refetched once)
- Proxy matcher excludes only exact /login and /api/auth/ paths

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 20:12:39 +02:00

248 lines
8.2 KiB
TypeScript

// Minimal Hugging Face Hub API client (metadata only; downloads go through the `hf` CLI).
// Server-side only: it reads HF_TOKEN from the environment. Never import from client components.
import { coreEnv } from "@/lib/env";
import { parseRepoMetadata, type RepoMetadata } from "./metadata";
const HUB = "https://huggingface.co";
const TIMEOUT_MS = 20_000;
const USER_AGENT = "kaname-model-manager";
export const REPO_ID_RE = /^[A-Za-z0-9][\w.-]*\/[A-Za-z0-9][\w.-]*$/;
export const SHA_RE = /^[0-9a-f]{40}$/;
export type HubErrorCode =
| "invalid_repo_id"
| "invalid_token"
| "repo_not_found" // or private without access
| "revision_not_found"
| "gated_no_token"
| "gated_no_access"
| "rate_limited"
| "network"
| "unknown";
export class HubError extends Error {
constructor(
public code: HubErrorCode,
message: string,
public status?: number,
) {
super(message);
this.name = "HubError";
}
}
export type HubFile = {
path: string;
size: number;
/** Git blob SHA-1. */
blobOid: string;
/** SHA-256 of the content, for LFS/Xet files. */
lfsSha256: string | null;
xetHash: string | null;
};
export type RepoInfo = {
repoId: string;
sha: string;
gated: false | "auto" | "manual";
private: boolean;
lastModified: string | null;
metadata: RepoMetadata;
};
function headers(): HeadersInit {
const h: Record<string, string> = { "User-Agent": USER_AGENT };
const token = coreEnv().HF_TOKEN;
if (token) h.Authorization = `Bearer ${token}`;
return h;
}
async function hubFetch(url: string, init: RequestInit = {}): Promise<Response> {
try {
return await fetch(url, {
...init,
headers: { ...headers(), ...init.headers },
cache: "no-store",
signal: AbortSignal.timeout(TIMEOUT_MS),
});
} catch (err) {
const reason = err instanceof Error ? err.message : String(err);
throw new HubError("network", `Could not reach huggingface.co (${reason}).`);
}
}
/** Is the configured token valid? Only called after a 401, to tell a bad token from a missing repo. */
async function tokenIsValid(): Promise<boolean> {
const res = await hubFetch(`${HUB}/api/whoami-v2`);
return res.ok;
}
async function toHubError(res: Response, repoId: string, revision?: string): Promise<HubError> {
const code = res.headers.get("x-error-code");
const hasToken = Boolean(coreEnv().HF_TOKEN);
if (code === "RevisionNotFound") {
return new HubError("revision_not_found", `Revision "${revision}" not found in ${repoId}.`, res.status);
}
if (code === "GatedRepo") {
return hasToken
? new HubError(
"gated_no_access",
`${repoId} is gated and this token's account has not been granted access. Request access at ${HUB}/${repoId}.`,
res.status,
)
: new HubError(
"gated_no_token",
`${repoId} is gated. Set HF_TOKEN for an account that has accepted the terms at ${HUB}/${repoId}.`,
res.status,
);
}
if (res.status === 429) {
return new HubError("rate_limited", "Hugging Face rate limit hit. Try again in a minute.", res.status);
}
// The Hub answers 401 (without an error code) for missing repos when unauthenticated,
// and 401 for any request when the token is invalid.
if (res.status === 401 || res.status === 404 || code === "RepoNotFound") {
if (res.status === 401 && hasToken && !(await tokenIsValid())) {
return new HubError("invalid_token", "HF_TOKEN is invalid or expired.", res.status);
}
return new HubError(
"repo_not_found",
hasToken
? `Repository ${repoId} not found, or this token has no access to it.`
: `Repository ${repoId} not found. If it is private, set HF_TOKEN.`,
res.status,
);
}
const msg = res.headers.get("x-error-message") ?? res.statusText;
return new HubError("unknown", `Hugging Face API error ${res.status}: ${msg}`, res.status);
}
function assertRepoId(repoId: string) {
if (!REPO_ID_RE.test(repoId) || repoId.split("/").some((p) => p === "." || p === "..")) {
throw new HubError("invalid_repo_id", `"${repoId}" is not a valid repo ID (expected "org/name").`);
}
}
const enc = (s: string) => encodeURIComponent(s);
const repoPath = (repoId: string) => repoId.split("/").map(enc).join("/");
/** Resolve a branch, tag or commit to its full commit SHA, plus basic repo info. */
export async function getRepoInfo(repoId: string, revision: string): Promise<RepoInfo> {
assertRepoId(repoId);
const res = await hubFetch(`${HUB}/api/models/${repoPath(repoId)}/revision/${enc(revision)}`);
if (!res.ok) throw await toHubError(res, repoId, revision);
const j = (await res.json()) as {
id: string;
sha: string;
gated?: false | "auto" | "manual";
private?: boolean;
lastModified?: string;
} & Parameters<typeof parseRepoMetadata>[0];
return {
repoId: j.id ?? repoId,
sha: j.sha,
gated: j.gated ?? false,
private: j.private ?? false,
lastModified: j.lastModified ?? null,
metadata: parseRepoMetadata(j),
};
}
type TreeEntry = {
type: "file" | "directory";
path: string;
size: number;
oid: string;
lfs?: { oid: string; size: number };
xetHash?: string;
};
/** All files (recursive) at a commit. Follows the Link header for pagination. */
export async function listFiles(repoId: string, sha: string): Promise<HubFile[]> {
assertRepoId(repoId);
const files: HubFile[] = [];
let url: string | null =
`${HUB}/api/models/${repoPath(repoId)}/tree/${enc(sha)}?recursive=true&expand=false&limit=1000`;
while (url) {
const res = await hubFetch(url);
if (!res.ok) throw await toHubError(res, repoId, sha);
for (const e of (await res.json()) as TreeEntry[]) {
if (e.type !== "file") continue;
files.push({
path: e.path,
size: e.size,
blobOid: e.oid,
lfsSha256: e.lfs?.oid ?? null,
xetHash: e.xetHash ?? null,
});
}
url = nextLink(res.headers.get("link"));
}
return files.sort((a, b) => a.path.localeCompare(b.path));
}
function nextLink(link: string | null): string | null {
if (!link) return null;
for (const part of link.split(",")) {
const m = part.match(/<([^>]+)>\s*;\s*rel="?next"?/);
if (m) return m[1];
}
return null;
}
/** Avatar URL of a Hub org or user, or null. Best effort: errors are swallowed. */
export async function getAuthorAvatar(name: string): Promise<string | null> {
for (const path of [`organizations/${enc(name)}/avatar`, `users/${enc(name)}/overview`]) {
try {
const res = await hubFetch(`${HUB}/api/${path}`);
if (!res.ok) continue;
const j = (await res.json()) as { avatarUrl?: string };
if (j.avatarUrl?.startsWith("https://")) return j.avatarUrl;
} catch {
// ignore, try next
}
}
return null;
}
/**
* For gated repos the file list is public, but downloads need accepted terms.
* Probe one file with a HEAD request (no body is downloaded) to find out early.
*/
export async function checkFileAccess(repoId: string, sha: string, path: string): Promise<void> {
const url = `${HUB}/${repoPath(repoId)}/resolve/${enc(sha)}/${path.split("/").map(enc).join("/")}`;
const res = await hubFetch(url, { method: "HEAD", redirect: "manual" });
if (res.ok || (res.status >= 300 && res.status < 400)) return;
throw await toHubError(res, repoId, sha);
}
const cardCache = new Map<string, string | null>();
const CARD_CACHE_MAX = 100;
const CARD_MAX_BYTES = 512 * 1024;
/**
* The repo's README.md at a commit, without YAML front matter. Null if there is none.
* Cached in memory: a commit's content never changes.
*/
export async function fetchModelCard(repoId: string, sha: string): Promise<string | null> {
assertRepoId(repoId);
const key = `${repoId}@${sha}`;
if (cardCache.has(key)) return cardCache.get(key)!;
const res = await hubFetch(`${HUB}/${repoPath(repoId)}/raw/${enc(sha)}/README.md`);
if (res.status === 404) {
cardCache.set(key, null);
return null;
}
if (!res.ok) throw await toHubError(res, repoId, sha);
let text = (await res.text()).slice(0, CARD_MAX_BYTES);
text = text.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n/, "").trim();
if (cardCache.size >= CARD_CACHE_MAX) cardCache.delete(cardCache.keys().next().value!);
cardCache.set(key, text || null);
return text || null;
}