- Rename the app to Kaname - Hub metadata per model (base models, architecture, license, Hub tags), backfilled by the worker for existing models - Library search across repo/author/family/quant/tags and multi-select facet filters (author, family, quant, tag, status) kept in the URL - Custom tags (model page editor, on add, click-to-filter) - README rewritten around a quick install, with banner and screenshots - deploy/compose.yaml: models in a host folder (KANAME_MODELS_DIR) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
2167ea0950
commit
67191b3e16
37 files changed
+2028
-206
No files matched your search
@@ -75,12 +75,53 @@ export const models = sqliteTable(
|
||||
lastCheckError: text("last_check_error"),
|
||||
lastVerifiedAt: ts("last_verified_at"),
|
||||
downloadedAt: ts("downloaded_at"),
|
||||
// Hub metadata (for search/filters), refreshed by the worker. Null until fetched.
|
||||
/** e.g. ["Qwen/Qwen3-8B"] (cardData.base_model, or base_model:* tags). */
|
||||
baseModels: text("base_models", { mode: "json" }).$type<string[]>(),
|
||||
/** e.g. "qwen3" (gguf.architecture or config.model_type). */
|
||||
architecture: text("architecture"),
|
||||
pipelineTag: text("pipeline_tag"),
|
||||
license: text("license"),
|
||||
/** Hub tags, minus noise like arxiv:/region:/deploy:. */
|
||||
hubTags: text("hub_tags", { mode: "json" }).$type<string[]>(),
|
||||
metadataFetchedAt: ts("metadata_fetched_at"),
|
||||
createdAt: createdAt(),
|
||||
updatedAt: updatedAt(),
|
||||
},
|
||||
(t) => [uniqueIndex("models_repo_uq").on(t.repoType, t.repoId)],
|
||||
);
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// User tags (e.g. "roleplay", "security")
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export const tags = sqliteTable(
|
||||
"tags",
|
||||
{
|
||||
id: id(),
|
||||
/** Display name as entered. */
|
||||
name: text("name").notNull(),
|
||||
/** Lowercased, trimmed name; unique. */
|
||||
slug: text("slug").notNull(),
|
||||
createdAt: createdAt(),
|
||||
},
|
||||
(t) => [uniqueIndex("tags_slug_uq").on(t.slug)],
|
||||
);
|
||||
|
||||
export const modelTags = sqliteTable(
|
||||
"model_tags",
|
||||
{
|
||||
modelId: text("model_id")
|
||||
.notNull()
|
||||
.references(() => models.id),
|
||||
tagId: text("tag_id")
|
||||
.notNull()
|
||||
.references(() => tags.id),
|
||||
createdAt: createdAt(),
|
||||
},
|
||||
(t) => [primaryKey({ columns: [t.modelId, t.tagId] }), index("model_tags_tag_idx").on(t.tagId)],
|
||||
);
|
||||
|
||||
/** History of SHAs a model has been pinned to. */
|
||||
export const modelRevisions = sqliteTable(
|
||||
"model_revisions",
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
// 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;
|
||||
@@ -48,6 +49,7 @@ export type RepoInfo = {
|
||||
gated: false | "auto" | "manual";
|
||||
private: boolean;
|
||||
lastModified: string | null;
|
||||
metadata: RepoMetadata;
|
||||
};
|
||||
|
||||
function headers(): HeadersInit {
|
||||
@@ -138,13 +140,14 @@ export async function getRepoInfo(repoId: string, revision: string): Promise<Rep
|
||||
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),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
// Pure helpers that turn Hub model info into searchable metadata. Shared by web and worker.
|
||||
|
||||
export type RepoMetadata = {
|
||||
author: string | null;
|
||||
baseModels: string[];
|
||||
architecture: string | null;
|
||||
pipelineTag: string | null;
|
||||
license: string | null;
|
||||
hubTags: string[];
|
||||
};
|
||||
|
||||
type HubModelInfo = {
|
||||
id?: string;
|
||||
author?: string;
|
||||
pipeline_tag?: string;
|
||||
tags?: string[];
|
||||
cardData?: { base_model?: string | string[]; license?: string | string[] } | null;
|
||||
gguf?: { architecture?: string } | null;
|
||||
config?: { model_type?: string } | null;
|
||||
};
|
||||
|
||||
/** Hub tags that carry no useful search signal (or are stored separately). */
|
||||
const NOISE_TAG = /^(arxiv|region|deploy|base_model|license|doi|dataset):|^(endpoints_compatible|autotrain_compatible|eval-results|text-generation-inference|conversational)$/;
|
||||
|
||||
const asArray = (v: string | string[] | undefined | null): string[] =>
|
||||
v == null ? [] : (Array.isArray(v) ? v : [v]).filter((x): x is string => typeof x === "string" && x.length > 0);
|
||||
|
||||
export function parseRepoMetadata(info: HubModelInfo): RepoMetadata {
|
||||
const tags = info.tags ?? [];
|
||||
|
||||
// Prefer the model card; fall back to "base_model:<relation>:<id>" / "base_model:<id>" tags.
|
||||
let baseModels = asArray(info.cardData?.base_model);
|
||||
if (baseModels.length === 0) {
|
||||
baseModels = tags
|
||||
.filter((t) => t.startsWith("base_model:"))
|
||||
.map((t) => t.split(":").at(-1)!)
|
||||
.filter((id) => id.includes("/"));
|
||||
}
|
||||
|
||||
const license = asArray(info.cardData?.license)[0] ?? tags.find((t) => t.startsWith("license:"))?.slice(8) ?? null;
|
||||
|
||||
return {
|
||||
author: info.author ?? info.id?.split("/")[0] ?? null,
|
||||
baseModels: [...new Set(baseModels)],
|
||||
architecture: info.gguf?.architecture ?? info.config?.model_type ?? null,
|
||||
pipelineTag: info.pipeline_tag ?? null,
|
||||
license,
|
||||
hubTags: [...new Set(tags.filter((t) => !NOISE_TAG.test(t)))],
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The model "family" for filtering: the org of the base model(s) (unsloth/Qwen3-8B-GGUF → "Qwen"),
|
||||
* or the repo's own org for original models without a base model.
|
||||
*/
|
||||
export function modelFamilies(repoId: string, baseModels: string[] | null | undefined): string[] {
|
||||
const orgs = (baseModels ?? []).map((b) => b.split("/")[0]).filter(Boolean);
|
||||
return orgs.length > 0 ? [...new Set(orgs)] : [repoId.split("/")[0]];
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import { eq, isNull } from "drizzle-orm";
|
||||
import { db } from "@/lib/db/client";
|
||||
import { models } from "@/lib/db/schema";
|
||||
import { getRepoInfo } from "./client";
|
||||
import type { RepoMetadata } from "./metadata";
|
||||
|
||||
/** Columns to write on `models` for fetched Hub metadata. */
|
||||
export function metadataColumns(meta: RepoMetadata) {
|
||||
return {
|
||||
baseModels: meta.baseModels,
|
||||
architecture: meta.architecture,
|
||||
pipelineTag: meta.pipelineTag,
|
||||
license: meta.license,
|
||||
hubTags: meta.hubTags,
|
||||
metadataFetchedAt: new Date(),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch Hub metadata for models that don't have it yet (added before metadata existed).
|
||||
* Returns how many were updated; failures are reported but don't stop the others.
|
||||
*/
|
||||
export async function backfillMetadata(onError: (repoId: string, err: unknown) => void): Promise<number> {
|
||||
const missing = await db()
|
||||
.select({ id: models.id, repoId: models.repoId, pinnedSha: models.pinnedSha })
|
||||
.from(models)
|
||||
.where(isNull(models.metadataFetchedAt));
|
||||
let updated = 0;
|
||||
for (const m of missing) {
|
||||
try {
|
||||
const info = await getRepoInfo(m.repoId, m.pinnedSha);
|
||||
await db().update(models).set(metadataColumns(info.metadata)).where(eq(models.id, m.id));
|
||||
updated++;
|
||||
} catch (err) {
|
||||
onError(m.repoId, err);
|
||||
}
|
||||
}
|
||||
return updated;
|
||||
}
|
||||
+35
-9
@@ -1,12 +1,14 @@
|
||||
import "server-only";
|
||||
import { and, asc, desc, eq, sql } from "drizzle-orm";
|
||||
import { db } from "@/lib/db/client";
|
||||
import { modelFiles, models } from "@/lib/db/schema";
|
||||
import { modelFiles, models, modelTags, tags } from "@/lib/db/schema";
|
||||
import { modelFamilies } from "@/lib/hub/metadata";
|
||||
import { quantGroup } from "@/lib/selection";
|
||||
import type { Tag } from "@/lib/tags";
|
||||
|
||||
export type LibraryRow = Awaited<ReturnType<typeof listLibrary>>[number];
|
||||
|
||||
/** Models with their selected-file totals and a short "which quant" label. */
|
||||
/** Models with selected-file totals, quant labels, Hub metadata and user tags. */
|
||||
export async function listLibrary() {
|
||||
const d = db();
|
||||
const rows = await d
|
||||
@@ -19,6 +21,11 @@ export async function listLibrary() {
|
||||
status: models.status,
|
||||
createdAt: models.createdAt,
|
||||
downloadedAt: models.downloadedAt,
|
||||
baseModels: models.baseModels,
|
||||
architecture: models.architecture,
|
||||
pipelineTag: models.pipelineTag,
|
||||
license: models.license,
|
||||
hubTags: models.hubTags,
|
||||
fileCount: sql<number>`count(${modelFiles.id})`,
|
||||
totalBytes: sql<number>`coalesce(sum(${modelFiles.size}), 0)`,
|
||||
})
|
||||
@@ -31,17 +38,24 @@ export async function listLibrary() {
|
||||
.select({ modelId: modelFiles.modelId, path: modelFiles.path })
|
||||
.from(modelFiles)
|
||||
.where(eq(modelFiles.selected, true));
|
||||
const quants = new Map<string, Set<string>>();
|
||||
for (const f of selected) {
|
||||
const g = quantGroup(f.path);
|
||||
if (!g) continue;
|
||||
if (!quants.has(f.modelId)) quants.set(f.modelId, new Set());
|
||||
quants.get(f.modelId)!.add(g);
|
||||
}
|
||||
const quants = groupBy(selected, (f) => f.modelId, (f) => quantGroup(f.path));
|
||||
|
||||
const tagRows = await d
|
||||
.select({ modelId: modelTags.modelId, id: tags.id, name: tags.name })
|
||||
.from(modelTags)
|
||||
.innerJoin(tags, eq(tags.id, modelTags.tagId))
|
||||
.orderBy(asc(tags.slug));
|
||||
const tagsByModel = new Map<string, Tag[]>();
|
||||
for (const t of tagRows) tagsByModel.set(t.modelId, [...(tagsByModel.get(t.modelId) ?? []), { id: t.id, name: t.name }]);
|
||||
|
||||
return rows.map((r) => ({
|
||||
...r,
|
||||
author: r.repoId.split("/")[0],
|
||||
families: modelFamilies(r.repoId, r.baseModels),
|
||||
baseModels: r.baseModels ?? [],
|
||||
hubTags: r.hubTags ?? [],
|
||||
quants: [...(quants.get(r.id) ?? [])].sort(),
|
||||
tags: tagsByModel.get(r.id) ?? [],
|
||||
}));
|
||||
}
|
||||
|
||||
@@ -56,3 +70,15 @@ export async function getModel(id: string) {
|
||||
.orderBy(asc(modelFiles.path));
|
||||
return { model, files };
|
||||
}
|
||||
|
||||
function groupBy<T>(items: T[], key: (t: T) => string, value: (t: T) => string | null) {
|
||||
const out = new Map<string, Set<string>>();
|
||||
for (const item of items) {
|
||||
const v = value(item);
|
||||
if (v == null) continue;
|
||||
const k = key(item);
|
||||
if (!out.has(k)) out.set(k, new Set());
|
||||
out.get(k)!.add(v);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
+6
-1
@@ -2,9 +2,11 @@ import "server-only";
|
||||
import { and, eq, sql } from "drizzle-orm";
|
||||
import { ulid } from "ulid";
|
||||
import { db } from "@/lib/db/client";
|
||||
import { jobs, modelFiles, modelRevisions, models } from "@/lib/db/schema";
|
||||
import { jobs, modelFiles, modelRevisions, models, modelTags } from "@/lib/db/schema";
|
||||
import { checkFileAccess, getRepoInfo, listFiles } from "@/lib/hub/client";
|
||||
import { metadataColumns } from "@/lib/hub/refresh";
|
||||
import { isSelected, type SelectionRule } from "@/lib/selection";
|
||||
import { deleteUnusedTags } from "@/lib/tags";
|
||||
|
||||
export class ModelError extends Error {
|
||||
constructor(
|
||||
@@ -67,6 +69,7 @@ export async function addModel(input: {
|
||||
localPath: repoId,
|
||||
includePatterns: input.rule.include,
|
||||
excludePatterns: input.rule.exclude,
|
||||
...metadataColumns(info.metadata),
|
||||
}),
|
||||
d.insert(modelRevisions).values({ modelId, sha: info.sha }),
|
||||
...chunk(fileRows, INSERT_CHUNK).map((c) => d.insert(modelFiles).values(c)),
|
||||
@@ -91,10 +94,12 @@ export async function removeModel(id: string): Promise<void> {
|
||||
);
|
||||
}
|
||||
await d.batch([
|
||||
d.delete(modelTags).where(eq(modelTags.modelId, id)),
|
||||
d.delete(modelFiles).where(eq(modelFiles.modelId, id)),
|
||||
d.delete(modelRevisions).where(eq(modelRevisions.modelId, id)),
|
||||
d.delete(models).where(eq(models.id, id)),
|
||||
]);
|
||||
await deleteUnusedTags();
|
||||
}
|
||||
|
||||
function chunk<T>(items: T[], size: number): T[][] {
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { describe, it } from "node:test";
|
||||
import { modelFamilies, parseRepoMetadata } from "./hub/metadata";
|
||||
import { EMPTY_FILTERS, facetCounts, matchesFilters, matchesQuery, type SearchableModel } from "./search";
|
||||
|
||||
describe("parseRepoMetadata (real Hub responses, trimmed)", () => {
|
||||
it("unsloth GGUF quant of Qwen", () => {
|
||||
const m = parseRepoMetadata({
|
||||
id: "unsloth/Qwen3-8B-GGUF",
|
||||
author: "unsloth",
|
||||
pipeline_tag: "text-generation",
|
||||
tags: ["transformers", "gguf", "qwen3", "qwen", "unsloth", "base_model:Qwen/Qwen3-8B", "base_model:quantized:Qwen/Qwen3-8B", "license:apache-2.0", "endpoints_compatible", "conversational", "arxiv:2309.00071"],
|
||||
cardData: { base_model: "Qwen/Qwen3-8B", license: "apache-2.0" },
|
||||
gguf: { architecture: "qwen3" },
|
||||
});
|
||||
assert.deepEqual(m.baseModels, ["Qwen/Qwen3-8B"]);
|
||||
assert.equal(m.architecture, "qwen3");
|
||||
assert.equal(m.license, "apache-2.0");
|
||||
assert.deepEqual(m.hubTags, ["transformers", "gguf", "qwen3", "qwen", "unsloth"]);
|
||||
assert.deepEqual(modelFamilies("unsloth/Qwen3-8B-GGUF", m.baseModels), ["Qwen"]);
|
||||
});
|
||||
|
||||
it("finetune with base_model as array and config.model_type", () => {
|
||||
const m = parseRepoMetadata({
|
||||
id: "TheDrummer/Cydonia-24B-v4.1",
|
||||
author: "TheDrummer",
|
||||
tags: ["safetensors", "mistral"],
|
||||
cardData: { base_model: ["mistralai/Mistral-Small-3.2-24B-Instruct-2507"] },
|
||||
config: { model_type: "mistral" },
|
||||
});
|
||||
assert.deepEqual(m.baseModels, ["mistralai/Mistral-Small-3.2-24B-Instruct-2507"]);
|
||||
assert.equal(m.architecture, "mistral");
|
||||
assert.deepEqual(modelFamilies("TheDrummer/Cydonia-24B-v4.1", m.baseModels), ["mistralai"]);
|
||||
});
|
||||
|
||||
it("falls back to base_model tags; original models are their own family", () => {
|
||||
const m = parseRepoMetadata({ id: "x/y", tags: ["base_model:finetune:Qwen/Qwen3-8B-Base"] });
|
||||
assert.deepEqual(m.baseModels, ["Qwen/Qwen3-8B-Base"]);
|
||||
assert.equal(m.author, "x");
|
||||
assert.deepEqual(modelFamilies("Qwen/Qwen3-8B", []), ["Qwen"]);
|
||||
});
|
||||
});
|
||||
|
||||
const model = (over: Partial<SearchableModel>): SearchableModel => ({
|
||||
repoId: "unsloth/Qwen3-8B-GGUF",
|
||||
author: "unsloth",
|
||||
families: ["Qwen"],
|
||||
baseModels: ["Qwen/Qwen3-8B"],
|
||||
architecture: "qwen3",
|
||||
quants: ["Q4_K_M"],
|
||||
tags: ["roleplay"],
|
||||
hubTags: ["gguf"],
|
||||
pipelineTag: "text-generation",
|
||||
license: "apache-2.0",
|
||||
status: "ready",
|
||||
...over,
|
||||
});
|
||||
|
||||
describe("matchesQuery", () => {
|
||||
it("matches author, family, quant and tags case-insensitively, all terms required", () => {
|
||||
const m = model({});
|
||||
assert.ok(matchesQuery(m, "qwen"));
|
||||
assert.ok(matchesQuery(m, "unsloth qwen"));
|
||||
assert.ok(matchesQuery(m, "q4_k_m"));
|
||||
assert.ok(matchesQuery(m, "ROLEPLAY"));
|
||||
assert.ok(matchesQuery(m, " "));
|
||||
assert.ok(!matchesQuery(m, "unsloth gemma"));
|
||||
});
|
||||
});
|
||||
|
||||
describe("filters and facet counts", () => {
|
||||
const models = [
|
||||
model({}),
|
||||
model({ repoId: "bartowski/Qwen_Qwen3-8B-GGUF", author: "bartowski", quants: ["Q6_K"], tags: [] }),
|
||||
model({ repoId: "unsloth/gemma-3-27b-it-GGUF", families: ["google"], quants: ["Q4_K_M"], tags: ["security"] }),
|
||||
];
|
||||
|
||||
it("ORs within a facet and ANDs across facets", () => {
|
||||
const f = { ...EMPTY_FILTERS, author: ["unsloth"], quant: ["Q4_K_M", "Q6_K"] };
|
||||
assert.deepEqual(
|
||||
models.filter((m) => matchesFilters(m, f)).map((m) => m.repoId),
|
||||
["unsloth/Qwen3-8B-GGUF", "unsloth/gemma-3-27b-it-GGUF"],
|
||||
);
|
||||
});
|
||||
|
||||
it("counts a facet without applying its own selection", () => {
|
||||
const f = { ...EMPTY_FILTERS, author: ["unsloth"] };
|
||||
assert.deepEqual(facetCounts(models, "author", "", f), [["unsloth", 2], ["bartowski", 1]]);
|
||||
assert.deepEqual(facetCounts(models, "family", "", f), [["google", 1], ["Qwen", 1]]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,88 @@
|
||||
// Library search and facet filtering (runs in the browser; the library is small).
|
||||
|
||||
export type SearchableModel = {
|
||||
repoId: string;
|
||||
author: string;
|
||||
families: string[];
|
||||
baseModels: string[];
|
||||
architecture: string | null;
|
||||
quants: string[];
|
||||
tags: string[];
|
||||
hubTags: string[];
|
||||
pipelineTag: string | null;
|
||||
license: string | null;
|
||||
status: string;
|
||||
};
|
||||
|
||||
export const FACETS = ["author", "family", "quant", "tag", "status"] as const;
|
||||
export type Facet = (typeof FACETS)[number];
|
||||
export type Filters = Record<Facet, string[]>;
|
||||
|
||||
export const EMPTY_FILTERS: Filters = { author: [], family: [], quant: [], tag: [], status: [] };
|
||||
|
||||
export function facetValues(m: SearchableModel, facet: Facet): string[] {
|
||||
switch (facet) {
|
||||
case "author":
|
||||
return [m.author];
|
||||
case "family":
|
||||
return m.families;
|
||||
case "quant":
|
||||
return m.quants;
|
||||
case "tag":
|
||||
return m.tags;
|
||||
case "status":
|
||||
return [m.status];
|
||||
}
|
||||
}
|
||||
|
||||
function haystack(m: SearchableModel): string {
|
||||
return [
|
||||
m.repoId,
|
||||
m.author,
|
||||
...m.families,
|
||||
...m.baseModels,
|
||||
m.architecture,
|
||||
...m.quants,
|
||||
...m.tags,
|
||||
...m.hubTags,
|
||||
m.pipelineTag,
|
||||
m.license,
|
||||
m.status,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(" ")
|
||||
.toLowerCase();
|
||||
}
|
||||
|
||||
/** Every whitespace-separated term must appear somewhere (case-insensitive substring). */
|
||||
export function matchesQuery(m: SearchableModel, query: string): boolean {
|
||||
const terms = query.toLowerCase().split(/\s+/).filter(Boolean);
|
||||
if (terms.length === 0) return true;
|
||||
const text = haystack(m);
|
||||
return terms.every((t) => text.includes(t));
|
||||
}
|
||||
|
||||
/** OR within a facet, AND across facets. Values compare case-insensitively. */
|
||||
export function matchesFilters(m: SearchableModel, filters: Filters, except?: Facet): boolean {
|
||||
return FACETS.every((facet) => {
|
||||
const wanted = filters[facet];
|
||||
if (facet === except || wanted.length === 0) return true;
|
||||
const have = facetValues(m, facet).map((v) => v.toLowerCase());
|
||||
return wanted.some((w) => have.includes(w.toLowerCase()));
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Value counts for one facet, computed over the models that match the query and all *other*
|
||||
* facets, so picking e.g. an author narrows the quant counts but not the author list itself.
|
||||
*/
|
||||
export function facetCounts(models: SearchableModel[], facet: Facet, query: string, filters: Filters) {
|
||||
const counts = new Map<string, number>();
|
||||
for (const m of models) {
|
||||
if (!matchesQuery(m, query) || !matchesFilters(m, filters, facet)) continue;
|
||||
for (const v of new Set(facetValues(m, facet))) counts.set(v, (counts.get(v) ?? 0) + 1);
|
||||
}
|
||||
// Keep selected values visible even if their count dropped to 0.
|
||||
for (const v of filters[facet]) if (!counts.has(v)) counts.set(v, 0);
|
||||
return [...counts.entries()].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0], undefined, { numeric: true }));
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
import "server-only";
|
||||
import { and, asc, eq, sql } from "drizzle-orm";
|
||||
import { ulid } from "ulid";
|
||||
import { db } from "@/lib/db/client";
|
||||
import { modelTags, models, tags } from "@/lib/db/schema";
|
||||
|
||||
export const TAG_MAX_LENGTH = 40;
|
||||
|
||||
export class TagError extends Error {
|
||||
constructor(
|
||||
public code: "invalid" | "not_found",
|
||||
message: string,
|
||||
public status: number,
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
export type Tag = { id: string; name: string };
|
||||
|
||||
/** Trim and collapse whitespace; the slug (lowercase) decides uniqueness. */
|
||||
export function normalizeTagName(raw: string): { name: string; slug: string } {
|
||||
const name = raw.trim().replace(/\s+/g, " ");
|
||||
if (!name) throw new TagError("invalid", "Tag name is empty.", 400);
|
||||
if (name.length > TAG_MAX_LENGTH) throw new TagError("invalid", `Tag names are at most ${TAG_MAX_LENGTH} characters.`, 400);
|
||||
return { name, slug: name.toLowerCase() };
|
||||
}
|
||||
|
||||
/** All tags with how many models use them (for autocomplete). */
|
||||
export async function listTags(): Promise<(Tag & { count: number })[]> {
|
||||
return db()
|
||||
.select({ id: tags.id, name: tags.name, count: sql<number>`count(${modelTags.modelId})` })
|
||||
.from(tags)
|
||||
.leftJoin(modelTags, eq(modelTags.tagId, tags.id))
|
||||
.groupBy(tags.id)
|
||||
.orderBy(asc(tags.slug));
|
||||
}
|
||||
|
||||
export async function modelTagList(modelId: string): Promise<Tag[]> {
|
||||
return db()
|
||||
.select({ id: tags.id, name: tags.name })
|
||||
.from(modelTags)
|
||||
.innerJoin(tags, eq(tags.id, modelTags.tagId))
|
||||
.where(eq(modelTags.modelId, modelId))
|
||||
.orderBy(asc(tags.slug));
|
||||
}
|
||||
|
||||
/** Attach a tag (created on first use; matched case-insensitively) to a model. */
|
||||
export async function addTag(modelId: string, rawName: string): Promise<Tag> {
|
||||
const { name, slug } = normalizeTagName(rawName);
|
||||
const d = db();
|
||||
const model = await d.query.models.findFirst({ columns: { id: true }, where: eq(models.id, modelId) });
|
||||
if (!model) throw new TagError("not_found", "Model not found.", 404);
|
||||
|
||||
await d.insert(tags).values({ id: ulid(), name, slug }).onConflictDoNothing({ target: tags.slug });
|
||||
const tag = await d.query.tags.findFirst({ columns: { id: true, name: true }, where: eq(tags.slug, slug) });
|
||||
if (!tag) throw new Error("tag vanished after insert");
|
||||
await d.insert(modelTags).values({ modelId, tagId: tag.id }).onConflictDoNothing();
|
||||
return tag;
|
||||
}
|
||||
|
||||
/** Detach a tag; tags no model uses anymore are deleted. */
|
||||
export async function removeTag(modelId: string, tagId: string): Promise<void> {
|
||||
const d = db();
|
||||
await d.delete(modelTags).where(and(eq(modelTags.modelId, modelId), eq(modelTags.tagId, tagId)));
|
||||
await deleteUnusedTags();
|
||||
}
|
||||
|
||||
export async function deleteUnusedTags(): Promise<void> {
|
||||
await db().run(sql`delete from ${tags} where ${tags.id} not in (select ${modelTags.tagId} from ${modelTags})`);
|
||||
}
|
||||
Reference in new issue
Block a user