⚡ Bolt: Cache parsed YAML to prevent repetitive synchronous file I/O (#91)

- Implement an in-memory `Map` to cache parsed YAML objects.
- Use `structuredClone` to prevent caller mutations from corrupting the cached object state.
- Implement negative caching for missing files.

Co-authored-by: google-labs-jules[bot] <161369871+google-labs-jules[bot]@users.noreply.github.com>
This commit is contained in:
Ralksta
2026-04-21 22:51:22 +02:00
committed by GitHub
parent 264e48b3cc
commit fef4c73e86

View File

@@ -2,15 +2,39 @@ import fs from 'fs';
import path from 'path';
import yaml from 'js-yaml';
// ⚡ Bolt Optimization: Cache parsed YAML to prevent repetitive synchronous
// file I/O and expensive parsing during production runtime.
const yamlCache = new Map<string, unknown>();
export function loadYaml<T>(filename: string): T | null {
const isProd = process.env.NODE_ENV === 'production';
if (isProd && yamlCache.has(filename)) {
const cached = yamlCache.get(filename);
// ⚡ Bolt Optimization: Use `structuredClone` to prevent caller mutations
// from corrupting the cached object state, while preserving JS native types.
return cached === null ? null : structuredClone(cached as T);
}
const yamlPath = path.join(process.cwd(), 'content', filename);
if (!fs.existsSync(yamlPath)) {
// ⚡ Bolt Optimization: Implement negative caching for missing files.
if (isProd) {
yamlCache.set(filename, null);
}
return null;
}
const raw = fs.readFileSync(yamlPath, 'utf8');
return (yaml.load(raw) || {}) as T;
const parsed = (yaml.load(raw) || {}) as T;
if (isProd) {
yamlCache.set(filename, parsed);
return structuredClone(parsed);
}
return parsed;
}
const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;