import { HTMLRewriter } from "https://ghuc.cc/worker-tools/html-rewriter/index.ts";
const rewriter = new HTMLRewriter()
.on("head", {
element(element: any) {
element.append(`<link rel="manifest" href="/manifest.json">`, {
html: true,
});
},
});
export type Handler = (req: Request) => Response | Promise<Response>;
export function pwa(handler: Handler, manifest: Partial<ManifestOptions>): Handler {
return async (req: Request) => {
const url = new URL(req.url);
if (url.pathname === "/manifest.json") {
return new Response(JSON.stringify(manifest), {
headers: {
"Content-Type": "application/json",
},
});
}
const res = await handler(req);
return url.pathname == "/" ? rewriter.transform(res) : res;
};
}
export interface ManifestOptions {
name: string
short_name: string
description: string
icons: IconResource[]
file_handlers: {
action: string
accept: Record<string, string[]>
}[]
start_url: string
scope: string
id: string
orientation: 'any' | 'natural' | 'landscape' | 'landscape-primary' | 'landscape-secondary' | 'portrait' | 'portrait-primary' | 'portrait-secondary'
display: Display
display_override: DisplayOverride[]
background_color: string
theme_color: string
dir: 'ltr' | 'rtl'