/** wedo-hub 中心通知:publish 后广播事件 / 定时轮询感知他人更新;不可用自动降级裸 git fetch * env: WEDO_HUB_URL / WEDO_HUB_TOKEN / WEDO_REPO(项目标识,hub按此隔离) */ import { git, gitTry, BRANCH } from "./git.js"; export const HUB = process.env.WEDO_HUB_URL || ""; export const HUB_TOKEN = process.env.WEDO_HUB_TOKEN || ""; export const REPO_ID = process.env.WEDO_REPO || "default"; let pendingNews = ""; let hubLastTs = 0; export async function hubNotify(commit, message, files) { if (!HUB) return; try { await fetch(HUB.replace(/\/$/, "") + "/events", { method: "POST", headers: { "content-type": "application/json", ...(HUB_TOKEN ? { "x-wedo-token": HUB_TOKEN } : {}) }, body: JSON.stringify({ repo: REPO_ID, user: git(["config", "user.name"]).trim() || "unknown", message, commit, files }), }); } catch (e) { console.error("[wedo] hub通知失败(不影响git):" + (e.message || e)); } } async function hubPoll() { if (!HUB) return false; try { const r = await fetch(`${HUB.replace(/\/$/, "")}/events?repo=${encodeURIComponent(REPO_ID)}&since=${hubLastTs}`, { headers: HUB_TOKEN ? { "x-wedo-token": HUB_TOKEN } : {} }); const data = JSON.parse(await r.text()); const evs = (data && data.events) || []; if (evs.length) { hubLastTs = evs[evs.length - 1].ts; pendingNews = evs.map(e => `${(e.commit || "").slice(0, 7)} ${e.user} ${e.message} (${(e.files || []).join(",")})`).join("\n"); console.error(`[wedo] 🔔 hub通知:远端有 ${evs.length} 个新改动:\n${pendingNews}`); } return true; } catch { return false; } } /** 定时静默检查:优先hub接口(业务级事件),降级裸git fetch(提交级比对) */ export function startPolling(intervalMs) { const tick = async () => { if (await hubPoll()) return; const r = gitTry(["fetch", "origin", "--quiet"]); if (!r.ok) return; const news = gitTry(["log", "--pretty=format:%h %an %s", `HEAD..origin/${BRANCH}`]).out.trim(); if (news) { pendingNews = news; console.error(`[wedo] 🔔 检测到远程新提交:\n${news}`); } }; setInterval(tick, intervalMs); } /** 取走并清空更新提醒(附加到工具返回,一次性) */ export function newsBanner() { if (!pendingNews) return ""; const b = `\n\n🔔【远程更新提醒】检测到未同步的远端改动:\n${pendingNews}\n(用 proto_sync {pull:true} 同步)`; pendingNews = ""; return b; }