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 host = url.host;
7 const route = url.pathname;
8 const pagesService = new PagesService({
9 domain: site.knotDomain,
10 ownerDid: site.ownerDid,
11 repoName: site.repoName,
12 branch: site.branch,
13 baseDir: site.baseDir,
14 notFoundFilepath: site.notFoundFilepath,
15 });
16 const { status, content, contentType } = await pagesService.getPage(route);
17 return new Response(content, {
18 status,
19 headers: { "Content-Type": contentType },
20 });
21}
22
23export default {
24 async fetch(request, env, ctx) {
25 const url = new URL(request.url);
26 const host = url.host;
27 const subdomainOffset = config.subdomainOffset ?? 2;
28 const subdomain = host.split(".").at((subdomainOffset + 1) * -1);
29 // Single site mode
30 if (!subdomain) {
31 if (config.site) {
32 return handleSiteRequest(request, config.site);
33 } else {
34 return new Response("Tangled pages is running!", { status: 200 });
35 }
36 }
37 // Multi site mode
38 const matchingSite = config.sites.find(
39 (site) => site.subdomain === subdomain
40 );
41 if (matchingSite) {
42 return handleSiteRequest(request, matchingSite);
43 }
44 return new Response("Not Found", { status: 404 });
45 },
46};