first commit
All checks were successful
Code quality checks / biome (push) Successful in 7s

This commit is contained in:
creations 2025-05-11 14:07:03 -04:00
commit 9389fd5f8c
Signed by: creations
GPG key ID: 8F553AA4320FC711
15 changed files with 418 additions and 0 deletions

76
src/index.ts Normal file
View file

@ -0,0 +1,76 @@
import {
environment,
forgejo,
verifyRequiredVariables,
} from "@config/environment";
import { logger } from "@creations.works/logger";
import { fetch, serve } from "bun";
import mime from "mime";
async function main(): Promise<void> {
verifyRequiredVariables();
serve({
port: environment.port,
hostname: environment.host,
async fetch(req) {
const url = new URL(req.url);
const parts = url.pathname.split("/").filter(Boolean);
if (parts.length < 1) {
return new Response("Not found", { status: 404 });
}
// Redirect /username → /username/ to make relative paths work -_-
if (
parts.length === 1 &&
!url.pathname.endsWith("/") &&
!url.pathname.includes(".")
) {
return Response.redirect(`${url.pathname}/`, 301);
}
const username = parts[0];
if (!username.match(/^[a-z0-9_-]+$/i)) {
return new Response("Not found", { status: 404 });
}
let filePath = parts.slice(1).join("/");
if (url.pathname.endsWith("/") || filePath === "") {
filePath += "index.html";
}
const apiUrl = `${forgejo.url}/api/v1/repos/${username}/${forgejo.repo}/raw/${filePath}?ref=${forgejo.branch}`;
logger.info(`Proxying: ${url.pathname}${apiUrl}`);
const res = await fetch(apiUrl, {
headers: {
Authorization: `token ${forgejo.token}`,
},
});
if (!res.ok) {
return new Response("File not found", { status: res.status });
}
const contentType = mime.getType(filePath) || "application/octet-stream";
return new Response(res.body, {
status: res.status,
headers: {
"Content-Type": contentType,
},
});
},
});
logger.info(
`Server running at http://${environment.host}:${environment.port}`,
);
}
main().catch((error: Error) => {
logger.error(["Error initializing the server:", error]);
process.exit(1);
});