openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
264 lines (263 loc) • 8.82 kB
JavaScript
import { o as normalizeLowercaseStringOrEmpty } from "./string-coerce-CCIiB4H7.mjs";
import { r as asNullableRecord } from "./record-coerce-CVPuDqcc.mjs";
import { i as isMissingPathError } from "./errno-DFcoqIT9.mjs";
import { f as safeStat } from "./path-existence-Co7-GyVr.mjs";
import { t as LruCache } from "./lru-cache-wquJPIr-.mjs";
import { t as escapeRegExp } from "./regexp-dj3rRPbj.mjs";
import "./errors-BKzCeTYb.mjs";
import { r as resolveOpenClawPackageRootSync } from "./openclaw-root-C-ayo09z.mjs";
import { createRequire } from "node:module";
import fs from "node:fs";
import { fileURLToPath } from "node:url";
import path from "node:path";
import { readFileDescriptorBoundedSync, readFileWindowFullySync } from "@openclaw/fs-safe/advanced";
import { safeStatSync } from "@openclaw/fs-safe/path";
import { isUtf8 } from "node:buffer";
//#region src/infra/git-root.ts
function walkUpFrom(e, t, n) {
let r = path.resolve(e);
for (let e = 0; t.maxDepth === void 0 || e < t.maxDepth; e += 1) {
const e = n(r);
if (e !== null && e !== void 0) return e;
const t = path.dirname(r);
if (t === r) break;
r = t;
}
return null;
}
function hasGitMarker(e) {
const t = safeStatSync(path.join(e, ".git"));
return t ? t.isDirectory() || t.isFile() : false;
}
function findGitRoot(e, t = {}) {
return walkUpFrom(e, t, (e) => hasGitMarker(e) ? e : null);
}
/** Prompt preparation must not block the Gateway while discovering external checkouts. */
async function findGitRootAsync(e) {
let t = path.resolve(e);
for (;;) {
const e = await safeStat(path.join(t, ".git"));
if (e?.isDirectory() || e?.isFile()) return t;
const n = path.dirname(t);
if (n === t) return null;
t = n;
}
}
function readGitMetadataFile(e, t = 1048576) {
const n = fs.openSync(e, fs.constants.O_RDONLY | (fs.constants.O_NONBLOCK ?? 0));
try {
const e = fs.fstatSync(n);
if (!e.isFile() || e.size > t) throw new Error("Git metadata is not a bounded regular file");
const r = readFileDescriptorBoundedSync(n, Math.min(e.size, t));
if (r.length !== e.size) throw new Error("Git metadata changed during its read");
return r;
} finally {
fs.closeSync(n);
}
}
function readGitDirectoryPointerTarget(e, t = "") {
const n = readGitMetadataFile(e);
const r = n.toString("utf8").replace(/[\r\n]+$/u, "");
if (!isUtf8(n) || !r.startsWith(t) || r.length === t.length || r.includes("\0")) throw new Error("Git directory pointer is incomplete or malformed");
const i = r.slice(t.length);
return path.isAbsolute(i) ? i : `${path.dirname(e)}${path.sep}${i}`;
}
function readGitDirectoryPointer(e, t = "") {
return fs.realpathSync.native(readGitDirectoryPointerTarget(e, t));
}
function resolveGitDirFromMarker(e) {
const t = path.join(e, ".git");
try {
const e = fs.statSync(t);
if (e.isDirectory()) return t;
if (!e.isFile()) return null;
return readGitDirectoryPointer(t, "gitdir: ");
} catch {
return null;
}
}
function resolveGitHeadPath(e, t = {}) {
return walkUpFrom(e, t, (e) => {
const t = resolveGitDirFromMarker(e);
return t ? path.join(t, "HEAD") : null;
});
}
/** Read at most `limit` bytes from Git or build metadata. */
function readGitMetadataPrefix(e, t = 256) {
const n = fs.openSync(e, fs.constants.O_RDONLY | (fs.constants.O_NONBLOCK ?? 0));
try {
if (!fs.fstatSync(n).isFile()) throw new Error("Git metadata is not a regular file");
const e = Buffer.alloc(t);
const r = readFileWindowFullySync(n, e, 0);
return e.subarray(0, r).toString("utf-8");
} finally {
fs.closeSync(n);
}
}
function readGitHead(e, t = {}) {
const n = resolveGitHeadPath(e, t);
if (!n) return;
const r = readGitMetadataFile(n).toString("utf8").trim();
if (!r.startsWith("ref:")) return {
headPath: n,
ref: null,
value: r || null
};
const i = r.replace(/^ref:\s*/i, "").trim();
const a = resolveGitRefsBase(n);
return {
headPath: n,
ref: i,
value: readGitRefs(a, [i]).get(i) ?? null,
refsBase: a
};
}
function resolveGitRefsBase(e) {
const t = path.dirname(e);
const n = path.join(t, "commondir");
try {
return readGitDirectoryPointer(n);
} catch (e) {
if (!isMissingPathError(e) || fs.lstatSync(n, { throwIfNoEntry: false })) throw e;
}
return t;
}
/** Raw ref contents, sharing one packed inventory across the requested names. */
function readGitRefs(e, t) {
const n = new Map(t.map((e) => [e, null]));
const r = /* @__PURE__ */ new Set();
for (const i of t) {
const t = resolveRefPath(e, i);
if (!t) continue;
try {
n.set(i, readGitMetadataPrefix(t).trim());
} catch (e) {
if (!isMissingPathError(e)) throw e;
r.add(i);
}
}
if (r.size === 0) return n;
try {
const t = readGitMetadataFile(path.join(e, "packed-refs"), Number.MAX_SAFE_INTEGER).toString("utf8");
const i = new RegExp(`^(?![#^])[^\\S\\r\\n]*(\\S+)[^\\S\\r\\n]+(${[...r].map(escapeRegExp).join("|")})(?=\\s|$)`, "gm");
for (const [, e, a] of t.matchAll(i)) if (r.delete(a)) n.set(a, e);
} catch (e) {
if (!isMissingPathError(e)) throw e;
}
return n;
}
/** Safely resolve a Git ref path, rejecting traversal from a crafted HEAD file. */
function resolveRefPath(e, t) {
if (!t.startsWith("refs/")) return null;
if (t.split(/[/]/).includes("..")) return null;
const n = path.resolve(e, t);
const r = path.relative(e, n);
if (!r || r.startsWith("..") || path.isAbsolute(r)) return null;
return n;
}
//#endregion
//#region src/infra/git-commit.ts
const formatCommit = (e) => {
const t = e?.match(/[0-9a-fA-F]{7,40}/);
return t ? normalizeLowercaseStringOrEmpty(t[0].slice(0, 7)) : null;
};
function gitCommitPrefixesMatch(e, t) {
const n = normalizeLowercaseStringOrEmpty(e);
const r = normalizeLowercaseStringOrEmpty(t);
return n.length >= 7 && r.length >= 7 && (n.startsWith(r) || r.startsWith(n));
}
const cachedGitCommitBySearchDir = new LruCache(256);
const resolveCommitSearchDir = (e) => {
if (e.cwd) return path.resolve(e.cwd);
if (e.moduleUrl) try {
return path.dirname(fileURLToPath(e.moduleUrl));
} catch {}
return process.cwd();
};
const cacheGitCommit = (e, t) => {
cachedGitCommitBySearchDir.set(e, t);
return t;
};
const resolveGitLookupDepth = (e, t) => {
if (!t) return;
const n = path.relative(t, e);
if (n.startsWith("..") || path.isAbsolute(n)) return;
return (n ? n.split(path.sep).filter(Boolean).length : 0) + 1;
};
const readCommitFromGit = (e, t) => {
const n = readGitHead(e, { maxDepth: resolveGitLookupDepth(e, t) });
return n === void 0 ? void 0 : formatCommit(n.value);
};
const readCommitFromPackageJson = () => {
try {
const e = createRequire(import.meta.url)("../../package.json");
return formatCommit(e.gitHead ?? e.githead ?? null);
} catch {
return null;
}
};
const readCommitProbe = (e, t, n) => {
try {
for (const r of t) {
const t = fileURLToPath(new URL(r, e));
let i;
try {
i = readGitMetadataPrefix(t, 1024);
} catch (e) {
if (isMissingPathError(e)) continue;
return null;
}
try {
const e = asNullableRecord(JSON.parse(i))?.[n];
return typeof e === "string" ? formatCommit(e) : null;
} catch {
return null;
}
}
} catch {}
};
const readCommitFromBuildInfo = (e = import.meta.url) => {
return readCommitProbe(e, ["../build-info.json", "./build-info.json"], "commit") ?? null;
};
const readLoadedCommit = (e) => {
const t = readCommitProbe(e, ["../.buildstamp", "./.buildstamp"], "head");
const n = readCommitProbe(e, ["../.runtime-postbuildstamp", "./.runtime-postbuildstamp"], "head");
if (t !== void 0 || n !== void 0) {
if (t || n) return t && t === n ? t : null;
return readCommitFromBuildInfo(e);
}
return readCommitProbe(e, ["../build-info.json", "./build-info.json"], "commit");
};
const resolveCommitHash = (e = {}) => {
const t = e.env ?? process.env;
const n = t.GIT_COMMIT?.trim() || t.GIT_SHA?.trim();
const r = formatCommit(n);
if (r) return r;
const i = resolveCommitSearchDir(e);
const a = cachedGitCommitBySearchDir.get(i);
if (a !== void 0) return a;
const o = resolveOpenClawPackageRootSync({
cwd: e.cwd,
moduleUrl: e.moduleUrl
});
try {
const e = readCommitFromGit(i, o);
if (e !== void 0) return cacheGitCommit(i, e);
} catch {}
const s = readCommitFromBuildInfo();
if (s) return cacheGitCommit(i, s);
const c = readCommitFromPackageJson();
if (c) return cacheGitCommit(i, c);
return cacheGitCommit(i, null);
};
/** Resolve the commit that produced the loaded artifact, not the checkout's current revision. */
function resolveLoadedCommitHash(e = {}) {
const t = e.moduleUrl ?? import.meta.url;
const n = readLoadedCommit(t);
return n === void 0 ? resolveCommitHash({
moduleUrl: t,
...e.env ? { env: e.env } : {}
}) : n;
}
//#endregion
export { findGitRootAsync as a, findGitRoot as i, resolveCommitHash as n, resolveLoadedCommitHash as r, gitCommitPrefixesMatch as t };