files.ts

5.5 KB · raw

1import type { Context, Hono } from "hono";2import { isSafePath } from "../bucket/repo.ts";3import { type FileEntry, fileAt, headId, objectBytes, saveByPrefix } from "../mirror/queries.ts";4import { highlightLines } from "./highlight.ts";5import { type Html, html } from "./html.ts";6import {7	cacheFor,8	formatSize,9	notFound,10	openPublicRepo,11	type PageContext,12	page,13	pathUrl,14} from "./layout.ts";15import { renderMarkdown } from "./markdown.ts";1617const SHOWN_BYTES = 1024 * 1024;18const IMAGE = /\.(png|jpe?g|gif|webp|avif|ico|svg)$/i;19const MARKDOWN = /\.(md|markdown)$/i;20// Binary types a browser can show or save as they are; anything else textual stays21// text/plain (§21.8).22const PASS_THROUGH = /^(image|audio|video|font)\/|^application\/(pdf|zip|gzip|wasm)$/;2324type Found = {25	repo: string;26	path: string;27	at: string | null;28	file: FileEntry;29	bytes: Uint8Array<ArrayBuffer>;30};3132export function registerFileRoutes(app: Hono, ctx: PageContext): void {33	app.get("/:repo/files/:path{.+}", async (c) => {34		const found = findFile(c, ctx);35		if (!found) return notFound(c, ctx);36		cacheFor(c, found.at !== null);37		const title = found.path.split("/").pop() as string;38		const body = html`${breadcrumb(found)}39<h1 class="file-page-title">${title}</h1>40${await fileBody(found, c.req.query("view") === "source")}`;41		return c.html(42			page(ctx, {43				title: `${title} · ${found.repo}`,44				description: found.path,45				path: c.req.path,46				body,47			}),48		);49	});5051	app.get("/:repo/raw/:path{.+}", (c) => {52		const found = findFile(c, ctx);53		if (!found) return notFound(c, ctx);54		cacheFor(c, found.at !== null);55		const type = contentType(found.path, found.bytes);56		c.header("Content-Type", type);57		if (type === "image/svg+xml") c.header("Content-Security-Policy", "sandbox");58		return c.body(found.bytes);59	});60}6162/** The file named by the route at `?at=<id>` or HEAD, behind the visibility gate; null means 404. */63function findFile(c: Context, ctx: PageContext): Found | null {64	const name = c.req.param("repo") as string;65	const path = c.req.param("path") as string;66	const repo = openPublicRepo(ctx, name);67	if (!repo || !isSafePath(path)) return null;68	const at = c.req.query("at") ?? null;69	const saveId = at === null ? headId(repo.mirror) : (saveByPrefix(repo.mirror, at)?.id ?? null);70	const file = saveId ? fileAt(repo.mirror, saveId, path) : null;71	const bytes = file && objectBytes(repo.mirror, file.hash);72	return file && bytes ? { repo: name, path, at: at && saveId, file, bytes } : null;73}7475export function isText(bytes: Uint8Array): boolean {76	if (bytes.subarray(0, 8000).includes(0)) return false;77	try {78		// Streaming mode tolerates only a character cut at the 1 MB mark; invalid bytes still throw.79		const cut = bytes.length > SHOWN_BYTES;80		new TextDecoder("utf-8", { fatal: true }).decode(bytes.subarray(0, SHOWN_BYTES), {81			stream: cut,82		});83		return true;84	} catch {85		return false;86	}87}8889function contentType(path: string, bytes: Uint8Array): string {90	const type = Bun.file(path).type;91	if (type.startsWith("image/")) return type;92	if (isText(bytes)) return "text/plain; charset=utf-8";93	return PASS_THROUGH.test(type) ? type : "application/octet-stream";94}9596function rawHref(found: Found): string {97	return `/${found.repo}/raw/${pathUrl(found.path)}${found.at ? `?at=${found.at}` : ""}`;98}99100function breadcrumb(found: Found): Html {101	const dirs = found.path.split("/").slice(0, -1);102	return html`<p class="breadcrumb mono"><a href="/${103		found.repo104	}">${found.repo}</a>${dirs.map((dir) => ` / ${dir}`)}${found.at && html` @ <a href="/${found.repo}/saves/${found.at}">${found.at}</a>`}</p>`;105}106107async function fileBody(found: Found, source: boolean): Promise<Html> {108	const size = formatSize(found.file.size);109	const raw = rawHref(found);110	if (IMAGE.test(found.path)) {111		return html`<p class="file-meta mono">${112			size113		} · <a href="${raw}">raw</a></p><div class="file-image"><img src="${raw}" alt="${found.path}"></div>`;114	}115	if (!isText(found.bytes)) {116		return html`<p class="file-meta mono">binary file · ${117			size118		} · <a href="${raw}" download>download</a></p>`;119	}120	const truncated = found.bytes.length > SHOWN_BYTES;121	const text = new TextDecoder().decode(found.bytes.subarray(0, SHOWN_BYTES));122	const meta = html`<p class="file-meta mono">${123		size124	}${truncated && " · showing the first 1 MB"} · <a href="${raw}">raw</a></p>`;125	if (MARKDOWN.test(found.path)) {126		const at = found.at ? `at=${found.at}&` : "";127		const toggle = html`<p class="file-toggle mono"><a href="?${128			found.at ? `at=${found.at}` : ""129		}"${!source && html` class="active"`}>rendered</a> · <a href="?${at}view=source"${source && html` class="active"`}>source</a></p>`;130		if (!source) {131			const dir = found.path.split("/").slice(0, -1).join("/");132			const rendered = renderMarkdown(text, { repo: found.repo, dir, at: found.at });133			return html`${meta}${toggle}<div class="markdown file-markdown">${rendered}</div>`;134		}135		return html`${meta}${toggle}${await codeView(text, found.path)}`;136	}137	return html`${meta}${await codeView(text, found.path)}`;138}139140// Each line is its own anchor target, so `#L42` scrolls and highlights through CSS alone; the141// script only adds ranges (`#L42-L50`).142async function codeView(text: string, path: string): Promise<Html> {143	const lines = await highlightLines(text, path);144	return html`<div class="file-view"><pre class="code"><code>${lines.map(145		(line, i) =>146			html`<span class="line" id="L${147				i + 1148			}"><a class="ln" href="#L${i + 1}">${i + 1}</a><span class="lc">${line}</span></span>`,149	)}</code></pre></div>`;150}