From e10de3febffd3e3b7eaa3aed611aea03153e6a82 Mon Sep 17 00:00:00 2001
From: Jacky Zhao <j.zhao2k19@gmail.com>
Date: Tue, 22 Aug 2023 00:01:18 +0000
Subject: [PATCH] fix: server-handler crash from filename (closes #386)

---
 quartz/build.ts |   19 +++++++++++++------
 1 files changed, 13 insertions(+), 6 deletions(-)

diff --git a/quartz/build.ts b/quartz/build.ts
index b5b1f9e..0af39d0 100644
--- a/quartz/build.ts
+++ b/quartz/build.ts
@@ -16,6 +16,7 @@
 import { glob, toPosixPath } from "./util/glob"
 import { trace } from "./util/trace"
 import { options } from "./util/sourcemap"
+import { Mutex } from "async-mutex"
 
 async function buildQuartz(argv: Argv, clientRefresh: () => void) {
   const ctx: BuildCtx = {
@@ -77,10 +78,11 @@
   }
 
   const initialSlugs = ctx.allSlugs
-  let timeoutIds: Set<ReturnType<typeof setTimeout>> = new Set()
-  let toRebuild: Set<FilePath> = new Set()
-  let toRemove: Set<FilePath> = new Set()
-  let trackedAssets: Set<FilePath> = new Set()
+  const buildMutex = new Mutex()
+  const timeoutIds: Set<ReturnType<typeof setTimeout>> = new Set()
+  const toRebuild: Set<FilePath> = new Set()
+  const toRemove: Set<FilePath> = new Set()
+  const trackedAssets: Set<FilePath> = new Set()
   async function rebuild(fp: string, action: "add" | "change" | "delete") {
     // don't do anything for gitignored files
     if (ignored(fp)) {
@@ -106,11 +108,13 @@
       toRemove.add(filePath)
     }
 
-    timeoutIds.forEach((id) => clearTimeout(id))
-
     // debounce rebuilds every 250ms
     timeoutIds.add(
       setTimeout(async () => {
+        const release = await buildMutex.acquire()
+        timeoutIds.forEach((id) => clearTimeout(id))
+        timeoutIds.clear()
+
         const perf = new PerfTimer()
         console.log(chalk.yellow("Detected change, rebuilding..."))
         try {
@@ -131,6 +135,8 @@
             contentMap.delete(fp)
           }
 
+          // TODO: we can probably traverse the link graph to figure out what's safe to delete here
+          // instead of just deleting everything
           await rimraf(argv.output)
           const parsedFiles = [...contentMap.values()]
           const filteredContent = filterContent(ctx, parsedFiles)
@@ -143,6 +149,7 @@
         clientRefresh()
         toRebuild.clear()
         toRemove.clear()
+        release()
       }, 250),
     )
   }

--
Gitblit v1.10.0