1import type { Database } from "bun:sqlite";2import { blake3 } from "@noble/hashes/blake3.js";3import { bytesToHex } from "@noble/hashes/utils.js";4import { isSafePath } from "../bucket/repo.ts";5import type { FileEntry } from "./queries.ts";678export type ManifestEntry = {9 name: string;10 kind: "file" | "folder";11 hash: string;12 size: number;13 executable: boolean;14 manifest: string;15};1617const HEX64 = /^[0-9a-f]{64}$/;18const encoder = new TextEncoder();1920export function hashBody(body: string): string {21 return bytesToHex(blake3(encoder.encode(body)));22}232425export function parseManifest(body: string): ManifestEntry[] {26 const value = JSON.parse(body) as { entries?: unknown };27 if (typeof value !== "object" || value === null || !Array.isArray(value.entries)) {28 throw new Error("it has no entries");29 }30 const entries: ManifestEntry[] = [];31 for (const raw of value.entries) {32 const e = raw as Record<string, unknown>;33 if (typeof raw !== "object" || raw === null || typeof e.name !== "string" || e.name === "") {34 throw new Error("it has an entry with no name");35 }36 if (e.kind === "file") {37 if (typeof e.hash !== "string" || !HEX64.test(e.hash)) {38 throw new Error(`its entry ${e.name} has an invalid object hash`);39 }40 if (!Number.isSafeInteger(e.size) || (e.size as number) < 0) {41 throw new Error(`its entry ${e.name} has an invalid size`);42 }43 if (typeof e.executable !== "boolean") {44 throw new Error(`its entry ${e.name} has no executable bit`);45 }46 entries.push({47 name: e.name,48 kind: "file",49 hash: e.hash,50 size: e.size as number,51 executable: e.executable,52 manifest: "",53 });54 } else if (e.kind === "folder") {55 if (typeof e.manifest !== "string" || !HEX64.test(e.manifest)) {56 throw new Error(`its entry ${e.name} has an invalid manifest hash`);57 }58 entries.push({59 name: e.name,60 kind: "folder",61 hash: "",62 size: 0,63 executable: false,64 manifest: e.manifest,65 });66 } else {67 throw new Error(`its entry ${e.name} has an unknown kind`);68 }69 }70 return entries;71}727374export function flattenTree(read: (hash: string) => string, root: string): FileEntry[] {75 const files: FileEntry[] = [];76 walk(read, root, "", files, []);77 return files.sort((a, b) => byPath(a.path, b.path));78}7980function walk(81 read: (hash: string) => string,82 hash: string,83 prefix: string,84 out: FileEntry[],85 ancestors: string[],86): void {87 if (ancestors.includes(hash)) throw new Error(`manifest ${hash} refers to itself`);88 const deeper = [...ancestors, hash];89 for (const entry of parseManifest(read(hash))) {90 if (entry.kind === "file") {91 out.push({92 path: prefix + entry.name,93 hash: entry.hash,94 executable: entry.executable,95 size: entry.size,96 });97 } else {98 walk(read, entry.manifest, `${prefix}${entry.name}/`, out, deeper);99 }100 }101}102103104function byPath(a: string, b: string): number {105 for (let i = 0, j = 0; i < a.length && j < b.length; ) {106 const x = a.codePointAt(i) as number;107 const y = b.codePointAt(j) as number;108 if (x !== y) return x - y;109 i += x > 0xffff ? 2 : 1;110 j += y > 0xffff ? 2 : 1;111 }112 return a.length - b.length;113}114115116export function manifestBody(db: Database, hash: string): string | null {117 return (118 db.query<{ body: string }, [string]>("SELECT body FROM manifests WHERE hash = ?").get(hash)119 ?.body ?? null120 );121}122123124125126const flat = new Map<string, FileEntry[]>();127let flatEntries = 0;128const MAX_FLAT = 50_000;129130131132133134export function flattenManifest(db: Database, root: string): FileEntry[] {135 const cached = flat.get(root);136 if (cached) return cached;137 const files = flattenTree((hash) => {138 const body = manifestBody(db, hash);139 if (body === null) throw new Error(`manifest ${hash} is missing from the mirror`);140 return body;141 }, root).filter((file) => isSafePath(file.path));142 if (flatEntries + files.length > MAX_FLAT) {143 flat.clear();144 flatEntries = 0;145 }146 flat.set(root, files);147 flatEntries += files.length;148 return files;149}150151type Trie = {152 files: Map<string, { hash: string; executable: boolean }>;153 folders: Map<string, Trie>;154};155156157158159160161export function manifestTree(162 files: { path: string; hash: string; executable: boolean }[],163 sizeOf: (hash: string) => number | null,164): { root: string; bodies: Map<string, string> } {165 const top: Trie = { files: new Map(), folders: new Map() };166 for (const file of files) {167 const size = sizeOf(file.hash);168 169 170 if (size === null) continue;171 const parts = file.path.split("/");172 const name = parts.pop() as string;173 let node = top;174 for (const part of parts) {175 let child = node.folders.get(part);176 if (!child) {177 child = { files: new Map(), folders: new Map() };178 node.folders.set(part, child);179 }180 node = child;181 }182 node.files.set(name, { hash: file.hash, executable: file.executable });183 }184 const bodies = new Map<string, string>();185 const write = (node: Trie): string => {186 const entries: ManifestEntry[] = [];187 for (const [name, child] of node.folders) {188 entries.push({189 name,190 kind: "folder",191 hash: "",192 size: 0,193 executable: false,194 manifest: write(child),195 });196 }197 if (node.files.size > 0) {198 for (const [name, file] of node.files) {199 entries.push({200 name,201 kind: "file",202 hash: file.hash,203 size: sizeOf(file.hash) as number,204 executable: file.executable,205 manifest: "",206 });207 }208 }209 210 entries.sort((a, b) => {211 if (a.name !== b.name) return a.name < b.name ? -1 : 1;212 return (a.kind === "file" ? 0 : 1) - (b.kind === "file" ? 0 : 1);213 });214 const body = JSON.stringify({ entries });215 const hash = hashBody(body);216 bodies.set(hash, body);217 return hash;218 };219 return { root: write(top), bodies };220}