Files
Kaname/src/lib/hub/lookup.ts
T
Pascal LinxweilerandClaude Opus 5.5 8f7ac60ccf Milestone (b): repo lookup and file selection
- Hub API client: resolve revision to SHA, paginated recursive file tree,
  gated-access probe, readable error mapping
- Add-model page with quant quick-select, fnmatch-compatible include/exclude
  globs, selection summary and free-space hint
- Models stored pinned to the reviewed SHA with full file list and selection rule
- Library list, model detail page, remove (never-downloaded models only)
- Worker reports MODELS_DIR free space; unit tests for selection logic

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

58 lines
1.9 KiB
TypeScript

import "server-only";
import { and, eq } from "drizzle-orm";
import { db } from "@/lib/db/client";
import { models } from "@/lib/db/schema";
import { checkFileAccess, getRepoInfo, type HubFile, listFiles, type RepoInfo } from "./client";
export type LookupResult = {
repoId: string;
revision: string;
sha: string;
gated: RepoInfo["gated"];
lastModified: string | null;
files: HubFile[];
/** Set when this repo is already in the library. */
existingModelId: string | null;
};
/**
* Accept "org/name", or a pasted Hub URL like https://huggingface.co/org/name/tree/main.
* Returns the repo id and, if the URL contained one, the revision.
*/
export function normalizeRepoInput(input: string): { repoId: string; revision?: string } {
let s = input.trim();
const url = s.match(/^https?:\/\/(?:www\.)?huggingface\.co\/(.+)$/i);
if (url) s = url[1];
s = s.replace(/[?#].*$/, "").replace(/\/+$/, "");
const parts = s.split("/");
const repoId = parts.slice(0, 2).join("/");
const revision = parts[2] === "tree" || parts[2] === "blob" ? parts[3] : undefined;
return { repoId, revision };
}
/** Repo metadata + file list at the resolved commit, with an early access check for gated repos. */
export async function lookupRepo(repoId: string, revision: string): Promise<LookupResult> {
const info = await getRepoInfo(repoId, revision);
const files = await listFiles(info.repoId, info.sha);
if (info.gated && files.length > 0) {
const smallest = files.reduce((a, b) => (b.size < a.size ? b : a));
await checkFileAccess(info.repoId, info.sha, smallest.path);
}
const existing = await db().query.models.findFirst({
columns: { id: true },
where: and(eq(models.repoType, "model"), eq(models.repoId, info.repoId)),
});
return {
repoId: info.repoId,
revision,
sha: info.sha,
gated: info.gated,
lastModified: info.lastModified,
files,
existingModelId: existing?.id ?? null,
};
}