Skip to content

Commit ff48120

Browse files
authored
fix hello race condition (#1132)
1 parent 3982706 commit ff48120

File tree

1 file changed

+9
-6
lines changed

1 file changed

+9
-6
lines changed

src/preview.ts

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -223,9 +223,9 @@ export class PreviewServer {
223223
}
224224
};
225225

226-
_handleConnection = async (socket: WebSocket, req: IncomingMessage) => {
226+
_handleConnection = (socket: WebSocket, req: IncomingMessage) => {
227227
if (req.url === "/_observablehq") {
228-
handleWatch(socket, req, await this._readConfig());
228+
handleWatch(socket, req, this._readConfig()); // can’t await; messages would be dropped
229229
} else {
230230
socket.close();
231231
}
@@ -273,8 +273,8 @@ function getWatchFiles(resolvers: Resolvers): Iterable<string> {
273273
return files;
274274
}
275275

276-
function handleWatch(socket: WebSocket, req: IncomingMessage, config: Config) {
277-
const {root, loaders} = config;
276+
function handleWatch(socket: WebSocket, req: IncomingMessage, configPromise: Promise<Config>) {
277+
let config: Config | null = null;
278278
let path: string | null = null;
279279
let hash: string | null = null;
280280
let html: string[] | null = null;
@@ -289,7 +289,8 @@ function handleWatch(socket: WebSocket, req: IncomingMessage, config: Config) {
289289
console.log(faint("socket open"), req.url);
290290

291291
async function watcher(event: WatchEventType, force = false) {
292-
if (!path) throw new Error("not initialized");
292+
if (!path || !config) throw new Error("not initialized");
293+
const {root, loaders} = config;
293294
switch (event) {
294295
case "rename": {
295296
markdownWatcher?.close();
@@ -356,6 +357,8 @@ function handleWatch(socket: WebSocket, req: IncomingMessage, config: Config) {
356357
if (!(path = normalize(path)).startsWith("/")) throw new Error("Invalid path: " + initialPath);
357358
if (path.endsWith("/")) path += "index";
358359
path = join(dirname(path), basename(path, ".html") + ".md");
360+
config = await configPromise;
361+
const {root, loaders} = config;
359362
const source = await readFile(join(root, path), "utf8");
360363
const page = parseMarkdown(source, {path, ...config});
361364
const resolvers = await getResolvers(page, {root, path, loaders});
@@ -402,7 +405,7 @@ function handleWatch(socket: WebSocket, req: IncomingMessage, config: Config) {
402405
console.log(faint("socket close"), req.url);
403406
});
404407

405-
function send(message) {
408+
function send(message: any) {
406409
console.log(faint("↓"), message);
407410
socket.send(JSON.stringify(message));
408411
}

0 commit comments

Comments
 (0)