Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

9.2 KB
Raw Blame
import { randomUUID } from "node:crypto";
import fsSync from "node:fs";
import path from "node:path";
import { FsSafeError } from "./errors.js";
import { stringifyJsonDocument } from "./json-stringify.js";
import { readRegularFile, readRegularFileSync, statRegularFile } from "./regular-file.js";
import { openRootFileSync } from "./root-file.js";
import { writeTextAtomic } from "./text-atomic.js";
const READ_RETRY_MAX_ATTEMPTS = 5;
const READ_RETRY_BASE_DELAY_MS = 50;
function isRetryableReadError(err, options) {
    if (err instanceof FsSafeError && err.code === "path-mismatch") {
        return true;
    }
    if (options.retryOpenRaceErrors !== true) {
        return false;
    }
    const code = getErrorCode(err);
    return code === "ENOENT" || code === "EPERM";
}
function sleep(ms) {
    return new Promise((resolve) => setTimeout(resolve, ms));
}
async function readRegularFileWithRetry(filePath, options = {}) {
    let lastErr;
    for (let attempt = 0; attempt < READ_RETRY_MAX_ATTEMPTS; attempt++) {
        try {
            return (await readRegularFile({ filePath })).buffer;
        }
        catch (err) {
            lastErr = err;
            if (!isRetryableReadError(err, options) || attempt === READ_RETRY_MAX_ATTEMPTS - 1) {
                throw err;
            }
            await sleep(READ_RETRY_BASE_DELAY_MS * Math.pow(2, attempt));
        }
    }
    throw lastErr;
}
async function readRegularFileIfExistsWithRetry(filePath) {
    const initial = await statRegularFile(filePath);
    if (initial.missing) {
        return null;
    }
    return await readRegularFileWithRetry(filePath, { retryOpenRaceErrors: true });
}
const JSON_FILE_MODE = 0o600;
const JSON_DIR_MODE = 0o700;
const SUPPORTS_SYNC_NOFOLLOW = process.platform !== "win32" && "O_NOFOLLOW" in fsSync.constants;
function getErrorCode(err) {
    return err instanceof Error ? err.code : undefined;
}
function trySetSecureMode(pathname) {
    let fd;
    try {
        fd = fsSync.openSync(pathname, fsSync.constants.O_RDONLY |
            (SUPPORTS_SYNC_NOFOLLOW ? fsSync.constants.O_NOFOLLOW : 0));
        fsSync.fchmodSync(fd, JSON_FILE_MODE);
    }
    catch {
        // best-effort on platforms without chmod support
    }
    finally {
        if (fd !== undefined) {
            try {
                fsSync.closeSync(fd);
            }
            catch {
                // best-effort cleanup
            }
        }
    }
}
function trySyncDirectory(pathname) {
    let fd;
    try {
        fd = fsSync.openSync(path.dirname(pathname), "r");
        fsSync.fsyncSync(fd);
    }
    catch {
        // best-effort; some platforms/filesystems do not support syncing directories.
    }
    finally {
        if (fd !== undefined) {
            try {
                fsSync.closeSync(fd);
            }
            catch {
                // best-effort cleanup
            }
        }
    }
}
function renameJsonFileWithFallback(tmpPath, pathname) {
    try {
        fsSync.renameSync(tmpPath, pathname);
        return;
    }
    catch (error) {
        const code = error.code;
        if (code === "EPERM" || code === "EEXIST") {
            const existing = (() => {
                try {
                    return fsSync.lstatSync(pathname);
                }
                catch (lstatError) {
                    if (lstatError.code === "ENOENT") {
                        return null;
                    }
                    throw lstatError;
                }
            })();
            if (existing?.isSymbolicLink()) {
                fsSync.rmSync(pathname, { force: true });
                fsSync.renameSync(tmpPath, pathname);
                return;
            }
            fsSync.rmSync(pathname, { force: true });
            fsSync.renameSync(tmpPath, pathname);
            return;
        }
        throw error;
    }
}
function writeTempJsonFile(pathname, payload) {
    const fd = fsSync.openSync(pathname, "wx", JSON_FILE_MODE);
    try {
        fsSync.writeFileSync(fd, payload, "utf8");
        fsSync.fsyncSync(fd);
    }
    finally {
        fsSync.closeSync(fd);
    }
}
export function tryReadJsonSync(pathname) {
    try {
        const raw = readRegularFileSync({ filePath: pathname }).buffer.toString("utf8");
        return JSON.parse(raw);
    }
    catch {
        return null;
    }
}
export function writeJsonSync(pathname, data) {
    const targetPath = pathname;
    const tmpPath = `${targetPath}.${randomUUID()}.tmp`;
    const payload = `${stringifyJsonDocument(data, null, 2)}\n`;
    fsSync.mkdirSync(path.dirname(targetPath), { recursive: true, mode: JSON_DIR_MODE });
    try {
        writeTempJsonFile(tmpPath, payload);
        trySetSecureMode(tmpPath);
        renameJsonFileWithFallback(tmpPath, targetPath);
        trySetSecureMode(targetPath);
        trySyncDirectory(targetPath);
    }
    finally {
        try {
            fsSync.rmSync(tmpPath, { force: true });
        }
        catch {
            // best-effort cleanup when rename does not happen
        }
    }
}
export class JsonFileReadError extends Error {
    filePath;
    reason;
    constructor(filePath, reason, cause) {
        super(`Failed to ${reason} JSON file: ${filePath}`, { cause });
        this.name = "JsonFileReadError";
        this.filePath = filePath;
        this.reason = reason;
    }
}
function isRecord(value) {
    return typeof value === "object" && value !== null && !Array.isArray(value);
}
function resolveInvalidMessage(invalidMessage, relativePath) {
    if (typeof invalidMessage === "function") {
        return invalidMessage(relativePath);
    }
    return invalidMessage ?? `${relativePath} has an unexpected shape`;
}
export function readRootStructuredFileSync(options) {
    const absolutePath = path.resolve(options.rootDir, options.relativePath);
    const opened = openRootFileSync({
        absolutePath,
        rootPath: options.rootDir,
        ...(options.rootRealPath !== undefined ? { rootRealPath: options.rootRealPath } : {}),
        boundaryLabel: options.boundaryLabel,
        rejectHardlinks: options.rejectHardlinks,
        maxBytes: options.maxBytes,
        allowedType: "file",
    });
    if (!opened.ok) {
        return { ok: false, reason: "open", failure: opened };
    }
    try {
        const parsed = options.parse(fsSync.readFileSync(opened.fd, "utf8"));
        if (options.validate && !options.validate(parsed)) {
            return {
                ok: false,
                reason: "invalid",
                error: resolveInvalidMessage(options.invalidMessage, options.relativePath),
            };
        }
        return {
            ok: true,
            value: parsed,
            stat: opened.stat,
            path: opened.path,
            rootRealPath: opened.rootRealPath,
        };
    }
    catch (error) {
        return {
            ok: false,
            reason: "parse",
            error: `failed to parse ${options.relativePath}: ${String(error)}`,
        };
    }
    finally {
        fsSync.closeSync(opened.fd);
    }
}
export function readRootJsonSync(options) {
    return readRootStructuredFileSync({
        ...options,
        parse: (raw) => JSON.parse(raw),
    });
}
export function readRootJsonObjectSync(options) {
    return readRootStructuredFileSync({
        ...options,
        parse: (raw) => JSON.parse(raw),
        validate: isRecord,
        invalidMessage: (relativePath) => `${relativePath} must contain a JSON object`,
    });
}
export async function tryReadJson(filePath) {
    try {
        const buffer = await readRegularFileIfExistsWithRetry(filePath);
        if (buffer === null) {
            return null;
        }
        const raw = buffer.toString("utf8");
        return JSON.parse(raw);
    }
    catch {
        return null;
    }
}
export async function readJson(filePath) {
    let raw;
    try {
        raw = (await readRegularFileWithRetry(filePath, { retryOpenRaceErrors: true })).toString("utf8");
    }
    catch (err) {
        throw new JsonFileReadError(filePath, "read", err);
    }
    try {
        return JSON.parse(raw);
    }
    catch (err) {
        throw new JsonFileReadError(filePath, "parse", err);
    }
}
export async function readJsonIfExists(filePath) {
    let raw;
    try {
        const buffer = await readRegularFileIfExistsWithRetry(filePath);
        if (buffer === null) {
            return null;
        }
        raw = buffer.toString("utf8");
    }
    catch (err) {
        if (getErrorCode(err) === "ENOENT") {
            return null;
        }
        throw new JsonFileReadError(filePath, "read", err);
    }
    try {
        return JSON.parse(raw);
    }
    catch (err) {
        throw new JsonFileReadError(filePath, "parse", err);
    }
}
export function readJsonSync(filePath) {
    let raw;
    try {
        raw = readRegularFileSync({ filePath }).buffer.toString("utf8");
    }
    catch (err) {
        throw new JsonFileReadError(filePath, "read", err);
    }
    try {
        return JSON.parse(raw);
    }
    catch (err) {
        throw new JsonFileReadError(filePath, "parse", err);
    }
}
export async function writeJson(filePath, value, options) {
    const text = stringifyJsonDocument(value, null, 2);
    await writeTextAtomic(filePath, text, {
        mode: options?.mode,
        dirMode: options?.dirMode,
        trailingNewline: options?.trailingNewline,
        durable: options?.durable,
    });
}