Static site hosting via tangled
1import PagesService from "./pages-service.js";
2import config from "../config.worker.example.json"; // must be set at build time
3
4async function handleSiteRequest(request, site) {
5 const url = new URL(request.url);
6 const route = url.pathname;
7 const pagesService = new PagesService({
8 domain: site.knotDomain,
9 ownerDid: site.ownerDid,
10 repoName: site.repoName,
11 branch: site.branch,
12 baseDir: site.baseDir,
13 notFoundFilepath: site.notFoundFilepath,
14 });
15 const { status, content, contentType } = await pagesService.getPage(route);
16 return new Response(content, {
17 status,
18 headers: { "Content-Type": contentType },
19 });
20}
21
22export default {
23 async fetch(request, env, ctx) {
24 // Single site mode
25 if (config.site) {
26 return handleSiteRequest(request, config.site);
27 }
28 // Multi site mode
29 const url = new URL(request.url);
30 const subdomainOffset = config.subdomainOffset ?? 2;
31 const subdomain = url.host.split(".").at((subdomainOffset + 1) * -1);
32 if (!subdomain) {
33 return new Response("Tangled pages is running!", { status: 200 });
34 }
35 const matchingSite = config.sites?.find(
36 (site) => site.subdomain === subdomain
37 );
38 if (matchingSite) {
39 return handleSiteRequest(request, matchingSite);
40 }
41 return new Response("Not Found", { status: 404 });
42 },
43};