@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
72 lines • 3.29 kB
JavaScript
import { createHash } from "node:crypto";
import { mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
import { join } from "node:path";
// Entries are keyed by path, so stale ones only pile up when extensions move (a runtime update
// installs a new path). A real extension graph has thousands of modules, so the bound is age, not
// count: an entry nobody rewrote for this long is removed, and a still-used one is simply rebuilt.
const MAX_ENTRY_AGE_MS = 30 * 24 * 60 * 60 * 1000;
const sha256 = (text) => createHash("sha256").update(text).digest("hex");
function isPreparedSource(value) {
if (typeof value !== "object" || value === null)
return false;
const field = (name) => typeof Reflect.get(value, name);
return (field("key") === "string" &&
field("fingerprint") === "string" &&
field("token") === "string" &&
field("contents") === "string" &&
field("commonJs") === "boolean" &&
field("esmByType") === "boolean" &&
Array.isArray(Reflect.get(value, "edges")));
}
function prune(directory) {
const cutoff = Date.now() - MAX_ENTRY_AGE_MS;
for (const name of readdirSync(directory)) {
const path = join(directory, name);
if (statSync(path).mtimeMs < cutoff)
rmSync(path, { force: true });
}
}
/**
* Disk cache of the importer's transpile + import-rewrite output, so a fresh host skips that work
* for unchanged sources. `keyParts` is everything outside the source that shapes the output, as the
* importer passes it (release version, Bun version, runtime module path, extension namespace and the source
* of the code that prepares the bytes); `fingerprint` is the source hash.
* A miss, a corrupt entry and an unwritable directory all mean "prepare it again": the cache only
* ever saves time, so its I/O failures never reach the extension load.
*/
export function createPreparedSourceCache(directory, keyParts) {
const key = sha256(keyParts.join("\0"));
const entryPath = (filename) => join(directory, `${sha256(filename).slice(0, 40)}.json`);
let pruned = false;
return {
read(filename, fingerprint) {
let parsed;
try {
parsed = JSON.parse(readFileSync(entryPath(filename), "utf8"));
}
catch {
return undefined;
}
if (!isPreparedSource(parsed) || parsed.key !== key || parsed.fingerprint !== fingerprint)
return undefined;
return parsed;
},
write(filename, fingerprint, prepared) {
const target = entryPath(filename);
const temporary = `${target}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
try {
mkdirSync(directory, { recursive: true });
writeFileSync(temporary, JSON.stringify({ ...prepared, key, fingerprint }));
renameSync(temporary, target);
if (!pruned) {
pruned = true;
prune(directory);
}
}
catch {
rmSync(temporary, { force: true });
}
},
};
}
//# sourceMappingURL=bun-extension-prepared-cache.js.map