const normalize = (directory: string) => directory.replace(/[\\/]+$/, "") type State = | { status: "pending" } | { status: "ready" } | { status: "failed" message: string } const state = new Map() const waiters = new Map void>>() export const Worktree = { get(directory: string) { return state.get(normalize(directory)) }, pending(directory: string) { const key = normalize(directory) const current = state.get(key) if (current && current.status !== "pending") return state.set(key, { status: "pending" }) }, ready(directory: string) { const key = normalize(directory) state.set(key, { status: "ready" }) const list = waiters.get(key) if (!list) return waiters.delete(key) for (const fn of list) fn({ status: "ready" }) }, failed(directory: string, message: string) { const key = normalize(directory) state.set(key, { status: "failed", message }) const list = waiters.get(key) if (!list) return waiters.delete(key) for (const fn of list) fn({ status: "failed", message }) }, wait(directory: string) { const key = normalize(directory) const current = state.get(key) if (current && current.status !== "pending") return Promise.resolve(current) return new Promise((resolve) => { const list = waiters.get(key) if (!list) { waiters.set(key, [resolve]) return } list.push(resolve) }) }, }