Skip to content

Commit

Permalink
fix hello race condition (#1132)
Browse files Browse the repository at this point in the history
  • Loading branch information
mbostock committed Mar 23, 2024
1 parent 3982706 commit ff48120
Showing 1 changed file with 9 additions and 6 deletions.
15 changes: 9 additions & 6 deletions src/preview.ts
Expand Up @@ -223,9 +223,9 @@ export class PreviewServer {
}
};

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

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

async function watcher(event: WatchEventType, force = false) {
if (!path) throw new Error("not initialized");
if (!path || !config) throw new Error("not initialized");
const {root, loaders} = config;
switch (event) {
case "rename": {
markdownWatcher?.close();
Expand Down Expand Up @@ -356,6 +357,8 @@ function handleWatch(socket: WebSocket, req: IncomingMessage, config: Config) {
if (!(path = normalize(path)).startsWith("/")) throw new Error("Invalid path: " + initialPath);
if (path.endsWith("/")) path += "index";
path = join(dirname(path), basename(path, ".html") + ".md");
config = await configPromise;
const {root, loaders} = config;
const source = await readFile(join(root, path), "utf8");
const page = parseMarkdown(source, {path, ...config});
const resolvers = await getResolvers(page, {root, path, loaders});
Expand Down Expand Up @@ -402,7 +405,7 @@ function handleWatch(socket: WebSocket, req: IncomingMessage, config: Config) {
console.log(faint("socket close"), req.url);
});

function send(message) {
function send(message: any) {
console.log(faint("↓"), message);
socket.send(JSON.stringify(message));
}
Expand Down

0 comments on commit ff48120

Please sign in to comment.