Add development HTTP server

Add an HTTP server for development purposes that replies to requests
with both the static resources and on the fly generated pages.  This
serves the following needs.

- Modern module scripts requires an origin supporting CORS policies,
  which is not supported when pages are read from disk by the browser.

- Provide a way for implemting automatic reloading of pages when changes
  are made to the source files.

- Act as the starting point for making interactive features such as
  comments and analytics.
This commit is contained in:
Hornwitser 2025-02-02 10:03:55 +01:00
parent f708088ef7
commit 82323c9158
4 changed files with 201 additions and 1 deletions

21
cli.ts
View file

@ -4,6 +4,7 @@ import { prettify, htmlDocument } from "antihtml";
import { pages } from "./content/pages.js";
import type { Page } from "./content/types.js";
import { resolveRefs } from "./utils/resolve-refs.js";
import { createServer } from "./utils/http-server.js";
function pageToHtml(page: Page) {
if (!page.ref.startsWith("/")) {
@ -59,9 +60,27 @@ function build() {
}
}
function serve() {
const resources = assembleResources();
const server = createServer(
(ref) => {
const resource = resources.get(ref);
if (resource === undefined)
return undefined;
if (typeof resource === "string")
return fs.readFileSync(resource);
return Buffer.from(pageToHtml(resource));
}
);
server.listen(8080);
console.log("Listening on http://localhost:8080");
}
function printUsage() {
console.log("Usage: cli.js <cmd>");
console.log(" build - Copy resources and generated pages to build directory.");
console.log(" serve - Host website on localhost:8080 for development purposes.");
}
function main(runtime: string, script: string, args: string[]) {
@ -74,6 +93,8 @@ function main(runtime: string, script: string, args: string[]) {
const [command, ...commandArgs] = args;
if (command === "build") {
build();
} else if (command === "serve") {
serve();
} else {
console.log(`Error: Unkown sub-command ${command}`);
printUsage();