interface Env { CONTENT_VAULT: R2Bucket; HF_WEBHOOK_SECRET: string; HF_TOKEN: string; HF_REPO: string; HF_BASE_URL: string; } interface HFTreeItem { type: string; path: string; size?: number; } const CONTENT_TYPES: Record = { ".zip": "application/zip", ".yaml": "text/yaml", ".yml": "text/yaml", ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".json": "application/json", ".md": "text/markdown", ".txt": "text/plain", }; function getContentType(path: string): string { const ext = path.slice(path.lastIndexOf(".")).toLowerCase(); return CONTENT_TYPES[ext] || "application/octet-stream"; } async function listRepoFiles(baseUrl: string, repo: string, token: string): Promise { const files: string[] = []; async function fetchTree(path: string) { const url = `${baseUrl}/api/datasets/${repo}/tree/main${path ? "/" + path : ""}`; const resp = await fetch(url, { headers: token ? { Authorization: `Bearer ${token}` } : {}, }); if (!resp.ok) { throw new Error(`Failed to list ${url}: ${resp.status} ${resp.statusText}`); } const items: HFTreeItem[] = await resp.json(); for (const item of items) { if (item.type === "file") { files.push(item.path); } else if (item.type === "directory") { await fetchTree(item.path); } } } await fetchTree(""); return files; } async function syncFile( env: Env, filePath: string, ): Promise<{ path: string; status: string }> { const url = `${env.HF_BASE_URL}/datasets/${env.HF_REPO}/resolve/main/${encodeURIComponent(filePath)}`; const resp = await fetch(url, { headers: env.HF_TOKEN ? { Authorization: `Bearer ${env.HF_TOKEN}` } : {}, }); if (!resp.ok) { return { path: filePath, status: `error: ${resp.status}` }; } // R2 requires known content length. Use Content-Length header when available, // otherwise buffer into ArrayBuffer (works for files up to ~512MB Worker limit). const contentLength = resp.headers.get("Content-Length"); const body = contentLength ? resp.body : await resp.arrayBuffer(); await env.CONTENT_VAULT.put(filePath, body, { httpMetadata: { contentType: getContentType(filePath), cacheControl: "public, max-age=2592000", }, }); return { path: filePath, status: "ok" }; } export default { async fetch(request: Request, env: Env): Promise { if (request.method !== "POST") { return new Response("Method not allowed", { status: 405 }); } // Verify webhook secret const secret = request.headers.get("X-Webhook-Secret"); if (!secret || secret !== env.HF_WEBHOOK_SECRET) { return new Response("Unauthorized", { status: 401 }); } try { // List all files in the repo const files = await listRepoFiles(env.HF_BASE_URL, env.HF_REPO, env.HF_TOKEN); // Filter out git-related files const syncFiles = files.filter( (f) => !f.startsWith(".git") && f !== ".env", ); // Sync files sequentially to avoid memory pressure const results = []; for (const file of syncFiles) { const result = await syncFile(env, file); results.push(result); } const failed = results.filter((r) => r.status !== "ok"); return new Response( JSON.stringify({ synced: results.length, failed: failed.length, errors: failed, }), { headers: { "Content-Type": "application/json" }, }, ); } catch (err: unknown) { const message = err instanceof Error ? err.message : "Unknown error"; return new Response(JSON.stringify({ error: message }), { status: 500, headers: { "Content-Type": "application/json" }, }); } }, };