UNPKG

@intlayer/config

Version:

Retrieve Intlayer configurations and manage environment variables for both server-side and client-side environments.

182 lines (180 loc) 6.26 kB
import { clearAllCache, computeKeyId } from "./cacheMemory.mjs"; import { basename, dirname, join } from "node:path"; import { mkdir, readFile, rename, rm, stat, unlink, writeFile } from "node:fs/promises"; import { deserialize, serialize } from "node:v8"; import { gunzipSync, gzipSync } from "node:zlib"; import packageJSON from "@intlayer/types/package.json" with { type: "json" }; //#region src/utils/cacheDisk.ts const DEFAULTS = { compress: true }; const ensureDir = async (dir) => { await mkdir(dir, { recursive: true }); }; const atomicWriteFile = async (file, data, tempDir) => { if (tempDir) try { await ensureDir(tempDir); } catch {} const tempFileName = `${basename(file)}.tmp-${process.pid}-${Math.random().toString(36).slice(2)}`; const tmp = tempDir ? join(tempDir, tempFileName) : `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2)}`; try { await writeFile(tmp, data); await rename(tmp, file); } catch (error) { try { await rm(tmp, { force: true }); } catch {} throw error; } }; const shouldUseCompression = (buf, force) => force === true || force !== false && buf.byteLength > 1024; /** Derive on-disk path from config dir + namespace + key id. */ const cachePath = (cacheDir, id, ns) => join(cacheDir, ns ? join(ns, id) : id); /** ------------------------- Local cache facade ------------------------- **/ const cacheMap = /* @__PURE__ */ new Map(); /** Clears the in-memory portion of the disk cache without touching disk files. */ const clearDiskCacheMemory = () => { cacheMap.clear(); }; const cacheDisk = (intlayerConfig, keys, options) => { const { cacheDir, tempDir } = intlayerConfig.system; const buildCacheEnabled = intlayerConfig.build.cache ?? true; const persistent = options?.persistent === true || typeof options?.persistent === "undefined" && buildCacheEnabled; const { compress, ttlMs, maxTimeMs, namespace } = { ...DEFAULTS, ...options }; const id = computeKeyId(keys); const filePath = cachePath(cacheDir, id, namespace); const readFromDisk = async () => { try { const statValue = await stat(filePath).catch(() => void 0); if (!statValue) return void 0; if (typeof ttlMs === "number" && ttlMs > 0) { if (Date.now() - statValue.mtimeMs > ttlMs) return void 0; } let raw = await readFile(filePath); const flag = raw[0]; raw = raw.subarray(1); const deserialized = deserialize(flag === 1 ? gunzipSync(raw) : raw); let value; const maybeObj = deserialized; if (!!maybeObj && typeof maybeObj === "object" && typeof maybeObj.version === "string" && typeof maybeObj.timestamp === "number" && Object.hasOwn(maybeObj, "data")) { const entry = maybeObj; if (entry.version !== packageJSON.version) { try { await unlink(filePath); } catch {} return; } if (typeof maxTimeMs === "number" && maxTimeMs > 0) { if (Date.now() - entry.timestamp > maxTimeMs) { try { await unlink(filePath); } catch {} return; } } value = entry.data; } else { if (typeof maxTimeMs === "number" && maxTimeMs > 0) { if (Date.now() - statValue.mtimeMs > maxTimeMs) { try { await unlink(filePath); } catch {} return; } } value = deserialized; } cacheMap.set(id, value); return value; } catch { return; } }; const writeToDisk = async (value) => { try { await ensureDir(dirname(filePath)); const envelope = { version: packageJSON.version, timestamp: Date.now(), data: value }; const payload = Buffer.from(serialize(envelope)); const gz = shouldUseCompression(payload, compress) ? gzipSync(payload) : payload; await atomicWriteFile(filePath, Buffer.concat([Buffer.from([gz === payload ? 0 : 1]), gz]), tempDir); } catch {} }; return { /** In-memory first, then disk (if enabled), otherwise undefined. */ get: async () => { const mem = cacheMap.get(id); if (mem !== void 0) return mem; if (persistent && buildCacheEnabled) return await readFromDisk(); }, /** Sets in-memory (always) and persists to disk if enabled. */ set: async (value) => { cacheMap.set(id, value); if (persistent && buildCacheEnabled) await writeToDisk(value); }, /** Clears only this entry from memory and disk. */ clear: async () => { cacheMap.delete(id); try { await unlink(filePath); } catch {} }, /** Clears ALL cached entries (memory Map and entire cacheDir namespace if persistent). */ clearAll: async () => { clearAllCache(); if (persistent && buildCacheEnabled) { const base = namespace ? join(cacheDir, namespace) : cacheDir; try { await rm(base, { recursive: true, force: true }); } catch {} try { await mkdir(base, { recursive: true }); } catch {} } }, /** Expose the computed id (useful if you want to key other structures). */ isValid: async () => { if (cacheMap.get(id) !== void 0) return true; if (!persistent || !buildCacheEnabled) return false; try { const statValue = await stat(filePath).catch(() => void 0); if (!statValue) return false; if (typeof ttlMs === "number" && ttlMs > 0) { if (Date.now() - statValue.mtimeMs > ttlMs) return false; } let raw = await readFile(filePath); const flag = raw[0]; raw = raw.subarray(1); const maybeObj = deserialize(flag === 1 ? gunzipSync(raw) : raw); if (!!maybeObj && typeof maybeObj === "object" && typeof maybeObj.version === "string" && typeof maybeObj.timestamp === "number" && Object.hasOwn(maybeObj, "data")) { const entry = maybeObj; if (entry.version !== packageJSON.version) return false; if (typeof maxTimeMs === "number" && maxTimeMs > 0) { if (Date.now() - entry.timestamp > maxTimeMs) return false; } return true; } if (typeof maxTimeMs === "number" && maxTimeMs > 0) { if (Date.now() - statValue.mtimeMs > maxTimeMs) return false; } return true; } catch { return false; } }, /** Expose the computed id (useful if you want to key other structures). */ id, /** Expose the absolute file path for debugging. */ filePath }; }; //#endregion export { cacheDisk, clearDiskCacheMemory }; //# sourceMappingURL=cacheDisk.mjs.map