about summary refs log tree commit diff stats
path: root/src/index.ts
diff options
context:
space:
mode:
Diffstat (limited to 'src/index.ts')
-rw-r--r--src/index.ts18
1 files changed, 15 insertions, 3 deletions
diff --git a/src/index.ts b/src/index.ts
index 8b8ab0b..790c856 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -15,7 +15,7 @@ type File = {
   filename: string;
   headers?: Record<string, string>;
   size: number;
-  mtime: string;
+  mtime: Date;
 };
 
 let files = new Map<string, File>();
@@ -33,7 +33,7 @@ function registerFile(pathname: string, filename: string, stat: Stats): void {
         ? Object.assign({}, defaultHeaders, { "cache-control": "no-cache" })
         : undefined,
     size: stat.size,
-    mtime: stat.mtime.toUTCString(),
+    mtime: stat.mtime,
   });
 }
 
@@ -67,7 +67,7 @@ async function serveFile(
   if (file && (await fsp.exists(file.filename))) {
     return new Response(Bun.file(file.filename), {
       headers: {
-        "last-modified": file.mtime,
+        "last-modified": file.mtime.toUTCString(),
         ...(file.headers || defaultHeaders),
       },
       status: statusCode,
@@ -77,10 +77,22 @@ async function serveFile(
   }
 }
 
+function parseIfModifiedSinceHeader(header: string | null): number {
+  return header ? new Date(header).getTime() + 999 : 0;
+}
+
 export default withHtmlLiveReload({
   fetch: async function (request) {
     const pathname = new URL(request.url).pathname;
     const file = files.get(pathname);
+    if (file) {
+      const ims = parseIfModifiedSinceHeader(
+        request.headers.get("if-modified-since"),
+      );
+      if (ims >= file?.mtime.getTime()) {
+        return new Response("", { status: 304 });
+      }
+    }
     return serveFile(file);
   },
 });